aboutsummaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorArthurHoaro <arthur@hoa.ro>2016-05-18 21:48:24 +0200
committerArthurHoaro <arthur@hoa.ro>2016-06-11 09:30:56 +0200
commit684e662a58b02bde225e44d3677987b6fc3adf0b (patch)
treedb0d4ca1d9b53341cc108b0e7671ffde0e9caee9
parent59404d7909b21682ec0782778452a8a70e38b25e (diff)
downloadShaarli-684e662a58b02bde225e44d3677987b6fc3adf0b.tar.gz
Shaarli-684e662a58b02bde225e44d3677987b6fc3adf0b.tar.zst
Shaarli-684e662a58b02bde225e44d3677987b6fc3adf0b.zip
Replace $GLOBALS configuration with the configuration manager in the whole code base
-rw-r--r--application/ApplicationUtils.php26
-rw-r--r--application/Config.php221
-rw-r--r--application/FileUtils.php8
-rw-r--r--application/PageBuilder.php28
-rw-r--r--application/Updater.php30
-rw-r--r--application/Utils.php2
-rw-r--r--application/config/ConfigIO.php2
-rw-r--r--application/config/ConfigManager.php49
-rw-r--r--application/config/ConfigPhp.php3
-rw-r--r--application/config/ConfigPlugin.php4
-rw-r--r--index.php443
-rw-r--r--tests/ApplicationUtilsTest.php54
-rw-r--r--tests/ConfigTest.php244
-rw-r--r--tests/FeedBuilderTest.php6
-rw-r--r--tests/LinkDBTest.php2
-rw-r--r--tests/Updater/DummyUpdater.php5
-rw-r--r--tests/Updater/UpdaterTest.php80
-rw-r--r--tests/config/ConfigPhpTest.php16
-rw-r--r--tests/config/php/configOK.php14
-rw-r--r--tests/utils/config/configPhp.php14
-rw-r--r--tests/utils/config/configUpdater.php15
-rw-r--r--tpl/configure.html8
-rw-r--r--tpl/page.header.html4
23 files changed, 422 insertions, 856 deletions
diff --git a/application/ApplicationUtils.php b/application/ApplicationUtils.php
index 978fc9da..ed9abc39 100644
--- a/application/ApplicationUtils.php
+++ b/application/ApplicationUtils.php
@@ -132,32 +132,32 @@ class ApplicationUtils
132 /** 132 /**
133 * Checks Shaarli has the proper access permissions to its resources 133 * Checks Shaarli has the proper access permissions to its resources
134 * 134 *
135 * @param array $globalConfig The $GLOBALS['config'] array
136 *
137 * @return array A list of the detected configuration issues 135 * @return array A list of the detected configuration issues
138 */ 136 */
139 public static function checkResourcePermissions($globalConfig) 137 public static function checkResourcePermissions()
140 { 138 {
141 $errors = array(); 139 $errors = array();
140 $conf = ConfigManager::getInstance();
142 141
143 // Check script and template directories are readable 142 // Check script and template directories are readable
144 foreach (array( 143 foreach (array(
145 'application', 144 'application',
146 'inc', 145 'inc',
147 'plugins', 146 'plugins',
148 $globalConfig['RAINTPL_TPL'] 147 $conf->get('config.RAINTPL_TPL'),
149 ) as $path) { 148 ) as $path) {
150 if (! is_readable(realpath($path))) { 149 if (! is_readable(realpath($path))) {
151 $errors[] = '"'.$path.'" directory is not readable'; 150 $errors[] = '"'.$path.'" directory is not readable';
152 } 151 }
153 } 152 }
154 153
154 $datadir = $conf->get('config.DATADIR');
155 // Check cache and data directories are readable and writeable 155 // Check cache and data directories are readable and writeable
156 foreach (array( 156 foreach (array(
157 $globalConfig['CACHEDIR'], 157 $conf->get('config.CACHEDIR'),
158 $globalConfig['DATADIR'], 158 $datadir,
159 $globalConfig['PAGECACHE'], 159 $conf->get('config.PAGECACHE'),
160 $globalConfig['RAINTPL_TMP'] 160 $conf->get('config.RAINTPL_TMP'),
161 ) as $path) { 161 ) as $path) {
162 if (! is_readable(realpath($path))) { 162 if (! is_readable(realpath($path))) {
163 $errors[] = '"'.$path.'" directory is not readable'; 163 $errors[] = '"'.$path.'" directory is not readable';
@@ -169,11 +169,11 @@ class ApplicationUtils
169 169
170 // Check configuration files are readable and writeable 170 // Check configuration files are readable and writeable
171 foreach (array( 171 foreach (array(
172 $globalConfig['CONFIG_FILE'], 172 $conf->getConfigFile(),
173 $globalConfig['DATASTORE'], 173 $conf->get('config.DATASTORE'),
174 $globalConfig['IPBANS_FILENAME'], 174 $conf->get('config.IPBANS_FILENAME'),
175 $globalConfig['LOG_FILE'], 175 $conf->get('config.LOG_FILE'),
176 $globalConfig['UPDATECHECK_FILENAME'] 176 $conf->get('config.UPDATECHECK_FILENAME'),
177 ) as $path) { 177 ) as $path) {
178 if (! is_file(realpath($path))) { 178 if (! is_file(realpath($path))) {
179 # the file may not exist yet 179 # the file may not exist yet
diff --git a/application/Config.php b/application/Config.php
deleted file mode 100644
index 05a59452..00000000
--- a/application/Config.php
+++ /dev/null
@@ -1,221 +0,0 @@
1<?php
2/**
3 * Functions related to configuration management.
4 */
5
6/**
7 * Re-write configuration file according to given array.
8 * Requires mandatory fields listed in $MANDATORY_FIELDS.
9 *
10 * @param array $config contains all configuration fields.
11 * @param bool $isLoggedIn true if user is logged in.
12 *
13 * @return void
14 *
15 * @throws MissingFieldConfigException: a mandatory field has not been provided in $config.
16 * @throws UnauthorizedConfigException: user is not authorize to change configuration.
17 * @throws Exception: an error occured while writing the new config file.
18 */
19function writeConfig($config, $isLoggedIn)
20{
21 // These fields are required in configuration.
22 $MANDATORY_FIELDS = array(
23 'login', 'hash', 'salt', 'timezone', 'title', 'titleLink',
24 'redirector', 'disablesessionprotection', 'privateLinkByDefault'
25 );
26
27 if (!isset($config['config']['CONFIG_FILE'])) {
28 throw new MissingFieldConfigException('CONFIG_FILE');
29 }
30
31 // Only logged in user can alter config.
32 if (is_file($config['config']['CONFIG_FILE']) && !$isLoggedIn) {
33 throw new UnauthorizedConfigException();
34 }
35
36 // Check that all mandatory fields are provided in $config.
37 foreach ($MANDATORY_FIELDS as $field) {
38 if (!isset($config[$field])) {
39 throw new MissingFieldConfigException($field);
40 }
41 }
42
43 $configStr = '<?php '. PHP_EOL;
44 $configStr .= '$GLOBALS[\'login\'] = '.var_export($config['login'], true).';'. PHP_EOL;
45 $configStr .= '$GLOBALS[\'hash\'] = '.var_export($config['hash'], true).';'. PHP_EOL;
46 $configStr .= '$GLOBALS[\'salt\'] = '.var_export($config['salt'], true).'; '. PHP_EOL;
47 $configStr .= '$GLOBALS[\'timezone\'] = '.var_export($config['timezone'], true).';'. PHP_EOL;
48 $configStr .= 'date_default_timezone_set('.var_export($config['timezone'], true).');'. PHP_EOL;
49 $configStr .= '$GLOBALS[\'title\'] = '.var_export($config['title'], true).';'. PHP_EOL;
50 $configStr .= '$GLOBALS[\'titleLink\'] = '.var_export($config['titleLink'], true).'; '. PHP_EOL;
51 $configStr .= '$GLOBALS[\'redirector\'] = '.var_export($config['redirector'], true).'; '. PHP_EOL;
52 $configStr .= '$GLOBALS[\'disablesessionprotection\'] = '.var_export($config['disablesessionprotection'], true).'; '. PHP_EOL;
53 $configStr .= '$GLOBALS[\'privateLinkByDefault\'] = '.var_export($config['privateLinkByDefault'], true).'; '. PHP_EOL;
54
55 // Store all $config['config']
56 foreach ($config['config'] as $key => $value) {
57 $configStr .= '$GLOBALS[\'config\'][\''. $key .'\'] = '.var_export($config['config'][$key], true).';'. PHP_EOL;
58 }
59
60 if (isset($config['plugins'])) {
61 foreach ($config['plugins'] as $key => $value) {
62 $configStr .= '$GLOBALS[\'plugins\'][\''. $key .'\'] = '.var_export($config['plugins'][$key], true).';'. PHP_EOL;
63 }
64 }
65
66 if (!file_put_contents($config['config']['CONFIG_FILE'], $configStr)
67 || strcmp(file_get_contents($config['config']['CONFIG_FILE']), $configStr) != 0
68 ) {
69 throw new Exception(
70 'Shaarli could not create the config file.
71 Please make sure Shaarli has the right to write in the folder is it installed in.'
72 );
73 }
74}
75
76/**
77 * Process plugin administration form data and save it in an array.
78 *
79 * @param array $formData Data sent by the plugin admin form.
80 *
81 * @return array New list of enabled plugin, ordered.
82 *
83 * @throws PluginConfigOrderException Plugins can't be sorted because their order is invalid.
84 */
85function save_plugin_config($formData)
86{
87 // Make sure there are no duplicates in orders.
88 if (!validate_plugin_order($formData)) {
89 throw new PluginConfigOrderException();
90 }
91
92 $plugins = array();
93 $newEnabledPlugins = array();
94 foreach ($formData as $key => $data) {
95 if (startsWith($key, 'order')) {
96 continue;
97 }
98
99 // If there is no order, it means a disabled plugin has been enabled.
100 if (isset($formData['order_' . $key])) {
101 $plugins[(int) $formData['order_' . $key]] = $key;
102 }
103 else {
104 $newEnabledPlugins[] = $key;
105 }
106 }
107
108 // New enabled plugins will be added at the end of order.
109 $plugins = array_merge($plugins, $newEnabledPlugins);
110
111 // Sort plugins by order.
112 if (!ksort($plugins)) {
113 throw new PluginConfigOrderException();
114 }
115
116 $finalPlugins = array();
117 // Make plugins order continuous.
118 foreach ($plugins as $plugin) {
119 $finalPlugins[] = $plugin;
120 }
121
122 return $finalPlugins;
123}
124
125/**
126 * Validate plugin array submitted.
127 * Will fail if there is duplicate orders value.
128 *
129 * @param array $formData Data from submitted form.
130 *
131 * @return bool true if ok, false otherwise.
132 */
133function validate_plugin_order($formData)
134{
135 $orders = array();
136 foreach ($formData as $key => $value) {
137 // No duplicate order allowed.
138 if (in_array($value, $orders)) {
139 return false;
140 }
141
142 if (startsWith($key, 'order')) {
143 $orders[] = $value;
144 }
145 }
146
147 return true;
148}
149
150/**
151 * Affect plugin parameters values into plugins array.
152 *
153 * @param mixed $plugins Plugins array ($plugins[<plugin_name>]['parameters']['param_name'] = <value>.
154 * @param mixed $config Plugins configuration.
155 *
156 * @return mixed Updated $plugins array.
157 */
158function load_plugin_parameter_values($plugins, $config)
159{
160 $out = $plugins;
161 foreach ($plugins as $name => $plugin) {
162 if (empty($plugin['parameters'])) {
163 continue;
164 }
165
166 foreach ($plugin['parameters'] as $key => $param) {
167 if (!empty($config[$key])) {
168 $out[$name]['parameters'][$key] = $config[$key];
169 }
170 }
171 }
172
173 return $out;
174}
175
176/**
177 * Exception used if a mandatory field is missing in given configuration.
178 */
179class MissingFieldConfigException extends Exception
180{
181 public $field;
182
183 /**
184 * Construct exception.
185 *
186 * @param string $field field name missing.
187 */
188 public function __construct($field)
189 {
190 $this->field = $field;
191 $this->message = 'Configuration value is required for '. $this->field;
192 }
193}
194
195/**
196 * Exception used if an unauthorized attempt to edit configuration has been made.
197 */
198class UnauthorizedConfigException extends Exception
199{
200 /**
201 * Construct exception.
202 */
203 public function __construct()
204 {
205 $this->message = 'You are not authorized to alter config.';
206 }
207}
208
209/**
210 * Exception used if an error occur while saving plugin configuration.
211 */
212class PluginConfigOrderException extends Exception
213{
214 /**
215 * Construct exception.
216 */
217 public function __construct()
218 {
219 $this->message = 'An error occurred while trying to save plugins loading order.';
220 }
221}
diff --git a/application/FileUtils.php b/application/FileUtils.php
index 6a12ef0e..6cac9825 100644
--- a/application/FileUtils.php
+++ b/application/FileUtils.php
@@ -9,11 +9,13 @@ class IOException extends Exception
9 /** 9 /**
10 * Construct a new IOException 10 * Construct a new IOException
11 * 11 *
12 * @param string $path path to the ressource that cannot be accessed 12 * @param string $path path to the resource that cannot be accessed
13 * @param string $message Custom exception message.
13 */ 14 */
14 public function __construct($path) 15 public function __construct($path, $message = '')
15 { 16 {
16 $this->path = $path; 17 $this->path = $path;
17 $this->message = 'Error accessing '.$this->path; 18 $this->message = empty($message) ? 'Error accessing' : $message;
19 $this->message .= PHP_EOL . $this->path;
18 } 20 }
19} 21}
diff --git a/application/PageBuilder.php b/application/PageBuilder.php
index 82580787..cf13c714 100644
--- a/application/PageBuilder.php
+++ b/application/PageBuilder.php
@@ -29,21 +29,22 @@ class PageBuilder
29 private function initialize() 29 private function initialize()
30 { 30 {
31 $this->tpl = new RainTPL(); 31 $this->tpl = new RainTPL();
32 $conf = ConfigManager::getInstance();
32 33
33 try { 34 try {
34 $version = ApplicationUtils::checkUpdate( 35 $version = ApplicationUtils::checkUpdate(
35 shaarli_version, 36 shaarli_version,
36 $GLOBALS['config']['UPDATECHECK_FILENAME'], 37 $conf->get('config.UPDATECHECK_FILENAME'),
37 $GLOBALS['config']['UPDATECHECK_INTERVAL'], 38 $conf->get('config.UPDATECHECK_INTERVAL'),
38 $GLOBALS['config']['ENABLE_UPDATECHECK'], 39 $conf->get('config.ENABLE_UPDATECHECK'),
39 isLoggedIn(), 40 isLoggedIn(),
40 $GLOBALS['config']['UPDATECHECK_BRANCH'] 41 $conf->get('config.UPDATECHECK_BRANCH')
41 ); 42 );
42 $this->tpl->assign('newVersion', escape($version)); 43 $this->tpl->assign('newVersion', escape($version));
43 $this->tpl->assign('versionError', ''); 44 $this->tpl->assign('versionError', '');
44 45
45 } catch (Exception $exc) { 46 } catch (Exception $exc) {
46 logm($GLOBALS['config']['LOG_FILE'], $_SERVER['REMOTE_ADDR'], $exc->getMessage()); 47 logm($conf->get('config.LOG_FILE'), $_SERVER['REMOTE_ADDR'], $exc->getMessage());
47 $this->tpl->assign('newVersion', ''); 48 $this->tpl->assign('newVersion', '');
48 $this->tpl->assign('versionError', escape($exc->getMessage())); 49 $this->tpl->assign('versionError', escape($exc->getMessage()));
49 } 50 }
@@ -62,16 +63,19 @@ class PageBuilder
62 $this->tpl->assign('scripturl', index_url($_SERVER)); 63 $this->tpl->assign('scripturl', index_url($_SERVER));
63 $this->tpl->assign('pagetitle', 'Shaarli'); 64 $this->tpl->assign('pagetitle', 'Shaarli');
64 $this->tpl->assign('privateonly', !empty($_SESSION['privateonly'])); // Show only private links? 65 $this->tpl->assign('privateonly', !empty($_SESSION['privateonly'])); // Show only private links?
65 if (!empty($GLOBALS['title'])) { 66 if ($conf->exists('title')) {
66 $this->tpl->assign('pagetitle', $GLOBALS['title']); 67 $this->tpl->assign('pagetitle', $conf->get('title'));
67 } 68 }
68 if (!empty($GLOBALS['titleLink'])) { 69 if ($conf->exists('titleLink')) {
69 $this->tpl->assign('titleLink', $GLOBALS['titleLink']); 70 $this->tpl->assign('titleLink', $conf->get('titleLink'));
70 } 71 }
71 if (!empty($GLOBALS['pagetitle'])) { 72 if ($conf->exists('pagetitle')) {
72 $this->tpl->assign('pagetitle', $GLOBALS['pagetitle']); 73 $this->tpl->assign('pagetitle', $conf->get('pagetitle'));
73 } 74 }
74 $this->tpl->assign('shaarlititle', empty($GLOBALS['title']) ? 'Shaarli': $GLOBALS['title']); 75 $this->tpl->assign('shaarlititle', $conf->get('title', 'Shaarli'));
76 $this->tpl->assign('openshaarli', $conf->get('config.OPEN_SHAARLI', false));
77 $this->tpl->assign('showatom', $conf->get('config.SHOW_ATOM', false));
78 // FIXME! Globals
75 if (!empty($GLOBALS['plugin_errors'])) { 79 if (!empty($GLOBALS['plugin_errors'])) {
76 $this->tpl->assign('plugin_errors', $GLOBALS['plugin_errors']); 80 $this->tpl->assign('plugin_errors', $GLOBALS['plugin_errors']);
77 } 81 }
diff --git a/application/Updater.php b/application/Updater.php
index 58c13c07..6b92af3d 100644
--- a/application/Updater.php
+++ b/application/Updater.php
@@ -13,11 +13,6 @@ class Updater
13 protected $doneUpdates; 13 protected $doneUpdates;
14 14
15 /** 15 /**
16 * @var array Shaarli's configuration array.
17 */
18 protected $config;
19
20 /**
21 * @var LinkDB instance. 16 * @var LinkDB instance.
22 */ 17 */
23 protected $linkDB; 18 protected $linkDB;
@@ -36,14 +31,12 @@ class Updater
36 * Object constructor. 31 * Object constructor.
37 * 32 *
38 * @param array $doneUpdates Updates which are already done. 33 * @param array $doneUpdates Updates which are already done.
39 * @param array $config Shaarli's configuration array.
40 * @param LinkDB $linkDB LinkDB instance. 34 * @param LinkDB $linkDB LinkDB instance.
41 * @param boolean $isLoggedIn True if the user is logged in. 35 * @param boolean $isLoggedIn True if the user is logged in.
42 */ 36 */
43 public function __construct($doneUpdates, $config, $linkDB, $isLoggedIn) 37 public function __construct($doneUpdates, $linkDB, $isLoggedIn)
44 { 38 {
45 $this->doneUpdates = $doneUpdates; 39 $this->doneUpdates = $doneUpdates;
46 $this->config = $config;
47 $this->linkDB = $linkDB; 40 $this->linkDB = $linkDB;
48 $this->isLoggedIn = $isLoggedIn; 41 $this->isLoggedIn = $isLoggedIn;
49 42
@@ -114,19 +107,21 @@ class Updater
114 */ 107 */
115 public function updateMethodMergeDeprecatedConfigFile() 108 public function updateMethodMergeDeprecatedConfigFile()
116 { 109 {
117 $config_file = $this->config['config']['CONFIG_FILE']; 110 $conf = ConfigManager::getInstance();
118 111
119 if (is_file($this->config['config']['DATADIR'].'/options.php')) { 112 if (is_file($conf->get('config.DATADIR') . '/options.php')) {
120 include $this->config['config']['DATADIR'].'/options.php'; 113 include $conf->get('config.DATADIR') . '/options.php';
121 114
122 // Load GLOBALS into config 115 // Load GLOBALS into config
116 $allowedKeys = array_merge(ConfigPhp::$ROOT_KEYS);
117 $allowedKeys[] = 'config';
123 foreach ($GLOBALS as $key => $value) { 118 foreach ($GLOBALS as $key => $value) {
124 $this->config[$key] = $value; 119 if (in_array($key, $allowedKeys)) {
120 $conf->set($key, $value);
121 }
125 } 122 }
126 $this->config['config']['CONFIG_FILE'] = $config_file; 123 $conf->write($this->isLoggedIn);
127 writeConfig($this->config, $this->isLoggedIn); 124 unlink($conf->get('config.DATADIR').'/options.php');
128
129 unlink($this->config['config']['DATADIR'].'/options.php');
130 } 125 }
131 126
132 return true; 127 return true;
@@ -137,13 +132,14 @@ class Updater
137 */ 132 */
138 public function updateMethodRenameDashTags() 133 public function updateMethodRenameDashTags()
139 { 134 {
135 $conf = ConfigManager::getInstance();
140 $linklist = $this->linkDB->filterSearch(); 136 $linklist = $this->linkDB->filterSearch();
141 foreach ($linklist as $link) { 137 foreach ($linklist as $link) {
142 $link['tags'] = preg_replace('/(^| )\-/', '$1', $link['tags']); 138 $link['tags'] = preg_replace('/(^| )\-/', '$1', $link['tags']);
143 $link['tags'] = implode(' ', array_unique(LinkFilter::tagsStrToArray($link['tags'], true))); 139 $link['tags'] = implode(' ', array_unique(LinkFilter::tagsStrToArray($link['tags'], true)));
144 $this->linkDB[$link['linkdate']] = $link; 140 $this->linkDB[$link['linkdate']] = $link;
145 } 141 }
146 $this->linkDB->savedb($this->config['config']['PAGECACHE']); 142 $this->linkDB->savedb($conf->get('config.PAGECACHE'));
147 return true; 143 return true;
148 } 144 }
149} 145}
diff --git a/application/Utils.php b/application/Utils.php
index da521cce..9a8ca6d1 100644
--- a/application/Utils.php
+++ b/application/Utils.php
@@ -273,4 +273,4 @@ function autoLocale($headerLocale)
273 } 273 }
274 } 274 }
275 setlocale(LC_ALL, $attempts); 275 setlocale(LC_ALL, $attempts);
276} \ No newline at end of file 276}
diff --git a/application/config/ConfigIO.php b/application/config/ConfigIO.php
index 2b68fe6a..4b1c9901 100644
--- a/application/config/ConfigIO.php
+++ b/application/config/ConfigIO.php
@@ -21,6 +21,8 @@ interface ConfigIO
21 * 21 *
22 * @param string $filepath Config file absolute path. 22 * @param string $filepath Config file absolute path.
23 * @param array $conf All configuration in an array. 23 * @param array $conf All configuration in an array.
24 *
25 * @return bool True if the configuration has been successfully written, false otherwise.
24 */ 26 */
25 function write($filepath, $conf); 27 function write($filepath, $conf);
26 28
diff --git a/application/config/ConfigManager.php b/application/config/ConfigManager.php
index dfe9eeb9..212aac05 100644
--- a/application/config/ConfigManager.php
+++ b/application/config/ConfigManager.php
@@ -63,15 +63,24 @@ class ConfigManager
63 } 63 }
64 64
65 /** 65 /**
66 * Reset the ConfigManager instance.
67 */
68 public static function reset()
69 {
70 self::$instance = null;
71 return self::getInstance();
72 }
73
74 /**
66 * Rebuild the loaded config array from config files. 75 * Rebuild the loaded config array from config files.
67 */ 76 */
68 public function reload() 77 public function reload()
69 { 78 {
70 $this->initialize(); 79 $this->load();
71 } 80 }
72 81
73 /** 82 /**
74 * Initialize loaded conf in ConfigManager. 83 * Initialize the ConfigIO and loaded the conf.
75 */ 84 */
76 protected function initialize() 85 protected function initialize()
77 { 86 {
@@ -81,7 +90,15 @@ class ConfigManager
81 $this->configIO = new ConfigPhp(); 90 $this->configIO = new ConfigPhp();
82 }*/ 91 }*/
83 $this->configIO = new ConfigPhp(); 92 $this->configIO = new ConfigPhp();
84 $this->loadedConfig = $this->configIO->read(self::$CONFIG_FILE); 93 $this->load();
94 }
95
96 /**
97 * Load configuration in the ConfigurationManager.
98 */
99 protected function load()
100 {
101 $this->loadedConfig = $this->configIO->read($this->getConfigFile());
85 $this->setDefaultValues(); 102 $this->setDefaultValues();
86 } 103 }
87 104
@@ -117,9 +134,15 @@ class ConfigManager
117 * @param string $value Value to set. 134 * @param string $value Value to set.
118 * @param bool $write Write the new setting in the config file, default false. 135 * @param bool $write Write the new setting in the config file, default false.
119 * @param bool $isLoggedIn User login state, default false. 136 * @param bool $isLoggedIn User login state, default false.
137 *
138 * @throws Exception Invalid
120 */ 139 */
121 public function set($setting, $value, $write = false, $isLoggedIn = false) 140 public function set($setting, $value, $write = false, $isLoggedIn = false)
122 { 141 {
142 if (empty($setting) || ! is_string($setting)) {
143 throw new Exception('Invalid setting key parameter. String expected, got: '. gettype($setting));
144 }
145
123 $settings = explode('.', $setting); 146 $settings = explode('.', $setting);
124 self::setConfig($settings, $value, $this->loadedConfig); 147 self::setConfig($settings, $value, $this->loadedConfig);
125 if ($write) { 148 if ($write) {
@@ -151,6 +174,8 @@ class ConfigManager
151 * 174 *
152 * @param bool $isLoggedIn User login state. 175 * @param bool $isLoggedIn User login state.
153 * 176 *
177 * @return bool True if the configuration has been successfully written, false otherwise.
178 *
154 * @throws MissingFieldConfigException: a mandatory field has not been provided in $conf. 179 * @throws MissingFieldConfigException: a mandatory field has not been provided in $conf.
155 * @throws UnauthorizedConfigException: user is not authorize to change configuration. 180 * @throws UnauthorizedConfigException: user is not authorize to change configuration.
156 * @throws IOException: an error occurred while writing the new config file. 181 * @throws IOException: an error occurred while writing the new config file.
@@ -175,7 +200,7 @@ class ConfigManager
175 } 200 }
176 } 201 }
177 202
178 $this->configIO->write(self::$CONFIG_FILE, $this->loadedConfig); 203 return $this->configIO->write($this->getConfigFile(), $this->loadedConfig);
179 } 204 }
180 205
181 /** 206 /**
@@ -327,6 +352,22 @@ class ConfigManager
327 $this->set($key, $value); 352 $this->set($key, $value);
328 } 353 }
329 } 354 }
355
356 /**
357 * @return ConfigIO
358 */
359 public function getConfigIO()
360 {
361 return $this->configIO;
362 }
363
364 /**
365 * @param ConfigIO $configIO
366 */
367 public function setConfigIO($configIO)
368 {
369 $this->configIO = $configIO;
370 }
330} 371}
331 372
332/** 373/**
diff --git a/application/config/ConfigPhp.php b/application/config/ConfigPhp.php
index 311aeb81..19fecf2b 100644
--- a/application/config/ConfigPhp.php
+++ b/application/config/ConfigPhp.php
@@ -28,7 +28,6 @@ class ConfigPhp implements ConfigIO
28 */ 28 */
29 function read($filepath) 29 function read($filepath)
30 { 30 {
31 $filepath .= $this->getExtension();
32 if (! file_exists($filepath) || ! is_readable($filepath)) { 31 if (! file_exists($filepath) || ! is_readable($filepath)) {
33 return array(); 32 return array();
34 } 33 }
@@ -49,8 +48,6 @@ class ConfigPhp implements ConfigIO
49 */ 48 */
50 function write($filepath, $conf) 49 function write($filepath, $conf)
51 { 50 {
52 $filepath .= $this->getExtension();
53
54 $configStr = '<?php '. PHP_EOL; 51 $configStr = '<?php '. PHP_EOL;
55 foreach (self::$ROOT_KEYS as $key) { 52 foreach (self::$ROOT_KEYS as $key) {
56 if (isset($conf[$key])) { 53 if (isset($conf[$key])) {
diff --git a/application/config/ConfigPlugin.php b/application/config/ConfigPlugin.php
index 8af89d04..047d2b03 100644
--- a/application/config/ConfigPlugin.php
+++ b/application/config/ConfigPlugin.php
@@ -1,6 +1,8 @@
1<?php 1<?php
2/** 2/**
3 * Functions related to configuration management. 3 * Plugin configuration helper functions.
4 *
5 * Note: no access to configuration files here.
4 */ 6 */
5 7
6/** 8/**
diff --git a/index.php b/index.php
index 7465c41f..780dc581 100644
--- a/index.php
+++ b/index.php
@@ -22,114 +22,13 @@ if (date_default_timezone_get() == '') {
22 date_default_timezone_set('UTC'); 22 date_default_timezone_set('UTC');
23} 23}
24 24
25/* -----------------------------------------------------------------------------
26 * Hardcoded parameters
27 * You should not touch any code below (or at your own risks!)
28 * (These parameters can be overwritten by editing the file /data/config.php)
29 * -----------------------------------------------------------------------------
30 */
31
32/*
33 * Shaarli directories & configuration files
34 */
35// Data subdirectory
36$GLOBALS['config']['DATADIR'] = 'data';
37
38// Main configuration file
39$GLOBALS['config']['CONFIG_FILE'] = $GLOBALS['config']['DATADIR'].'/config.php';
40
41// Link datastore
42$GLOBALS['config']['DATASTORE'] = $GLOBALS['config']['DATADIR'].'/datastore.php';
43
44// Banned IPs
45$GLOBALS['config']['IPBANS_FILENAME'] = $GLOBALS['config']['DATADIR'].'/ipbans.php';
46
47// Processed updates file.
48$GLOBALS['config']['UPDATES_FILE'] = $GLOBALS['config']['DATADIR'].'/updates.txt';
49
50// Access log
51$GLOBALS['config']['LOG_FILE'] = $GLOBALS['config']['DATADIR'].'/log.txt';
52
53// For updates check of Shaarli
54$GLOBALS['config']['UPDATECHECK_FILENAME'] = $GLOBALS['config']['DATADIR'].'/lastupdatecheck.txt';
55
56// Set ENABLE_UPDATECHECK to disabled by default.
57$GLOBALS['config']['ENABLE_UPDATECHECK'] = false;
58
59// RainTPL cache directory (keep the trailing slash!)
60$GLOBALS['config']['RAINTPL_TMP'] = 'tmp/';
61// Raintpl template directory (keep the trailing slash!)
62$GLOBALS['config']['RAINTPL_TPL'] = 'tpl/';
63
64// Thumbnail cache directory
65$GLOBALS['config']['CACHEDIR'] = 'cache';
66
67// Atom & RSS feed cache directory
68$GLOBALS['config']['PAGECACHE'] = 'pagecache';
69
70/*
71 * Global configuration
72 */
73// Ban IP after this many failures
74$GLOBALS['config']['BAN_AFTER'] = 4;
75// Ban duration for IP address after login failures (in seconds)
76$GLOBALS['config']['BAN_DURATION'] = 1800;
77
78// Feed options
79// Enable RSS permalinks by default.
80// This corresponds to the default behavior of shaarli before this was added as an option.
81$GLOBALS['config']['ENABLE_RSS_PERMALINKS'] = true;
82// If true, an extra "ATOM feed" button will be displayed in the toolbar
83$GLOBALS['config']['SHOW_ATOM'] = false;
84
85// Link display options
86$GLOBALS['config']['HIDE_PUBLIC_LINKS'] = false;
87$GLOBALS['config']['HIDE_TIMESTAMPS'] = false;
88$GLOBALS['config']['LINKS_PER_PAGE'] = 20;
89
90// Open Shaarli (true): anyone can add/edit/delete links without having to login
91$GLOBALS['config']['OPEN_SHAARLI'] = false;
92
93// Thumbnails
94// Display thumbnails in links
95$GLOBALS['config']['ENABLE_THUMBNAILS'] = true;
96// Store thumbnails in a local cache
97$GLOBALS['config']['ENABLE_LOCALCACHE'] = true;
98
99// Update check frequency for Shaarli. 86400 seconds=24 hours
100$GLOBALS['config']['UPDATECHECK_BRANCH'] = 'stable';
101$GLOBALS['config']['UPDATECHECK_INTERVAL'] = 86400;
102
103$GLOBALS['config']['REDIRECTOR_URLENCODE'] = true;
104
105/*
106 * Plugin configuration
107 *
108 * Warning: order matters!
109 *
110 * These settings may be be overriden in:
111 * - data/config.php
112 * - each plugin's configuration file
113 */
114//$GLOBALS['config']['ENABLED_PLUGINS'] = array(
115// 'qrcode', 'archiveorg', 'readityourself', 'demo_plugin', 'playvideos',
116// 'wallabag', 'markdown', 'addlink_toolbar',
117//);
118$GLOBALS['config']['ENABLED_PLUGINS'] = array('qrcode');
119
120// Initialize plugin parameters array.
121$GLOBALS['plugins'] = array();
122
123// PubSubHubbub support. Put an empty string to disable, or put your hub url here to enable.
124$GLOBALS['config']['PUBSUBHUB_URL'] = '';
125
126/* 25/*
127 * PHP configuration 26 * PHP configuration
128 */ 27 */
129define('shaarli_version', '0.7.0'); 28define('shaarli_version', '0.7.0');
130 29
131// http://server.com/x/shaarli --> /shaarli/ 30// http://server.com/x/shaarli --> /shaarli/
132define('WEB_PATH', substr($_SERVER["REQUEST_URI"], 0, 1+strrpos($_SERVER["REQUEST_URI"], '/', 0))); 31define('WEB_PATH', substr($_SERVER['REQUEST_URI'], 0, 1+strrpos($_SERVER['REQUEST_URI'], '/', 0)));
133 32
134// High execution time in case of problematic imports/exports. 33// High execution time in case of problematic imports/exports.
135ini_set('max_input_time','60'); 34ini_set('max_input_time','60');
@@ -144,12 +43,6 @@ error_reporting(E_ALL^E_WARNING);
144// See all errors (for debugging only) 43// See all errors (for debugging only)
145//error_reporting(-1); 44//error_reporting(-1);
146 45
147/*
148 * User configuration
149 */
150if (is_file($GLOBALS['config']['CONFIG_FILE'])) {
151 require_once $GLOBALS['config']['CONFIG_FILE'];
152}
153 46
154// Shaarli library 47// Shaarli library
155require_once 'application/ApplicationUtils.php'; 48require_once 'application/ApplicationUtils.php';
@@ -166,10 +59,12 @@ require_once 'application/PageBuilder.php';
166require_once 'application/TimeZone.php'; 59require_once 'application/TimeZone.php';
167require_once 'application/Url.php'; 60require_once 'application/Url.php';
168require_once 'application/Utils.php'; 61require_once 'application/Utils.php';
169require_once 'application/Config.php'; 62require_once 'application/config/ConfigManager.php';
63require_once 'application/config/ConfigPlugin.php';
170require_once 'application/PluginManager.php'; 64require_once 'application/PluginManager.php';
171require_once 'application/Router.php'; 65require_once 'application/Router.php';
172require_once 'application/Updater.php'; 66require_once 'application/Updater.php';
67require_once 'inc/rain.tpl.class.php';
173 68
174// Ensure the PHP version is supported 69// Ensure the PHP version is supported
175try { 70try {
@@ -210,16 +105,16 @@ if (isset($_COOKIE['shaarli']) && !is_session_id_valid($_COOKIE['shaarli'])) {
210 $_COOKIE['shaarli'] = session_id(); 105 $_COOKIE['shaarli'] = session_id();
211} 106}
212 107
213include "inc/rain.tpl.class.php"; //include Rain TPL 108$conf = ConfigManager::getInstance();
214raintpl::$tpl_dir = $GLOBALS['config']['RAINTPL_TPL']; // template directory 109
215raintpl::$cache_dir = $GLOBALS['config']['RAINTPL_TMP']; // cache directory 110RainTPL::$tpl_dir = $conf->get('config.RAINTPL_TPL'); // template directory
111RainTPL::$cache_dir = $conf->get('config.RAINTPL_TMP'); // cache directory
216 112
217$pluginManager = PluginManager::getInstance(); 113$pluginManager = PluginManager::getInstance();
218$pluginManager->load($GLOBALS['config']['ENABLED_PLUGINS']); 114$pluginManager->load($conf->get('config.ENABLED_PLUGINS'));
219 115
220ob_start(); // Output buffering for the page cache. 116ob_start(); // Output buffering for the page cache.
221 117
222
223// In case stupid admin has left magic_quotes enabled in php.ini: 118// In case stupid admin has left magic_quotes enabled in php.ini:
224if (get_magic_quotes_gpc()) 119if (get_magic_quotes_gpc())
225{ 120{
@@ -236,17 +131,25 @@ header("Cache-Control: post-check=0, pre-check=0", false);
236header("Pragma: no-cache"); 131header("Pragma: no-cache");
237 132
238// Handling of old config file which do not have the new parameters. 133// Handling of old config file which do not have the new parameters.
239if (empty($GLOBALS['title'])) $GLOBALS['title']='Shared links on '.escape(index_url($_SERVER)); 134if (! $conf->exists('title')) {
240if (empty($GLOBALS['timezone'])) $GLOBALS['timezone']=date_default_timezone_get(); 135 $conf->set('title', 'Shared links on '. escape(index_url($_SERVER)));
241if (empty($GLOBALS['redirector'])) $GLOBALS['redirector']=''; 136}
242if (empty($GLOBALS['disablesessionprotection'])) $GLOBALS['disablesessionprotection']=false; 137if (! $conf->exists('timezone')) {
243if (empty($GLOBALS['privateLinkByDefault'])) $GLOBALS['privateLinkByDefault']=false; 138 $conf->set('timezone', date_default_timezone_get());
244if (empty($GLOBALS['titleLink'])) $GLOBALS['titleLink']='?'; 139}
245// I really need to rewrite Shaarli with a proper configuation manager. 140if (! $conf->exists('disablesessionprotection')) {
246 141 $conf->set('disablesessionprotection', false);
247if (! is_file($GLOBALS['config']['CONFIG_FILE'])) { 142}
143if (! $conf->exists('privateLinkByDefault')) {
144 $conf->set('privateLinkByDefault', false);
145}
146if (! $conf->exists('titleLink')) {
147 $conf->set('titleLink', '?');
148}
149
150if (! is_file($conf->getConfigFile())) {
248 // Ensure Shaarli has proper access to its resources 151 // Ensure Shaarli has proper access to its resources
249 $errors = ApplicationUtils::checkResourcePermissions($GLOBALS['config']); 152 $errors = ApplicationUtils::checkResourcePermissions();
250 153
251 if ($errors != array()) { 154 if ($errors != array()) {
252 $message = '<p>Insufficient permissions:</p><ul>'; 155 $message = '<p>Insufficient permissions:</p><ul>';
@@ -265,12 +168,13 @@ if (! is_file($GLOBALS['config']['CONFIG_FILE'])) {
265 install(); 168 install();
266} 169}
267 170
268$GLOBALS['title'] = !empty($GLOBALS['title']) ? escape($GLOBALS['title']) : ''; 171// FIXME! Update these value with Updater and escpae it during the install/config save.
269$GLOBALS['titleLink'] = !empty($GLOBALS['titleLink']) ? escape($GLOBALS['titleLink']) : ''; 172$conf->set('title', escape($conf->get('title')));
270$GLOBALS['redirector'] = !empty($GLOBALS['redirector']) ? escape($GLOBALS['redirector']) : ''; 173$conf->set('titleLink', escape($conf->get('titleLink')));
174$conf->set('redirector', escape($conf->get('redirector')));
271 175
272// a token depending of deployment salt, user password, and the current ip 176// a token depending of deployment salt, user password, and the current ip
273define('STAY_SIGNED_IN_TOKEN', sha1($GLOBALS['hash'].$_SERVER["REMOTE_ADDR"].$GLOBALS['salt'])); 177define('STAY_SIGNED_IN_TOKEN', sha1($conf->get('hash') . $_SERVER['REMOTE_ADDR'] . $conf->get('salt')));
274 178
275// Sniff browser language and set date format accordingly. 179// Sniff browser language and set date format accordingly.
276if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { 180if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
@@ -283,12 +187,14 @@ header('Content-Type: text/html; charset=utf-8'); // We use UTF-8 for proper int
283//================================================================================================== 187//==================================================================================================
284 188
285function setup_login_state() { 189function setup_login_state() {
286 if ($GLOBALS['config']['OPEN_SHAARLI']) { 190 $conf = ConfigManager::getInstance();
191
192 if ($conf->get('config.OPEN_SHAARLI')) {
287 return true; 193 return true;
288 } 194 }
289 $userIsLoggedIn = false; // By default, we do not consider the user as logged in; 195 $userIsLoggedIn = false; // By default, we do not consider the user as logged in;
290 $loginFailure = false; // If set to true, every attempt to authenticate the user will fail. This indicates that an important condition isn't met. 196 $loginFailure = false; // If set to true, every attempt to authenticate the user will fail. This indicates that an important condition isn't met.
291 if (!isset($GLOBALS['login'])) { 197 if (! $conf->exists('login')) {
292 $userIsLoggedIn = false; // Shaarli is not configured yet. 198 $userIsLoggedIn = false; // Shaarli is not configured yet.
293 $loginFailure = true; 199 $loginFailure = true;
294 } 200 }
@@ -300,9 +206,9 @@ function setup_login_state() {
300 $userIsLoggedIn = true; 206 $userIsLoggedIn = true;
301 } 207 }
302 // If session does not exist on server side, or IP address has changed, or session has expired, logout. 208 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
303 if (empty($_SESSION['uid']) || 209 if (empty($_SESSION['uid'])
304 ($GLOBALS['disablesessionprotection']==false && $_SESSION['ip']!=allIPs()) || 210 || ($conf->get('disablesessionprotection') == false && $_SESSION['ip'] != allIPs())
305 time() >= $_SESSION['expires_on']) 211 || time() >= $_SESSION['expires_on'])
306 { 212 {
307 logout(); 213 logout();
308 $userIsLoggedIn = false; 214 $userIsLoggedIn = false;
@@ -325,17 +231,19 @@ $userIsLoggedIn = setup_login_state();
325// ------------------------------------------------------------------------------------------ 231// ------------------------------------------------------------------------------------------
326// PubSubHubbub protocol support (if enabled) [UNTESTED] 232// PubSubHubbub protocol support (if enabled) [UNTESTED]
327// (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ ) 233// (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
328if (!empty($GLOBALS['config']['PUBSUBHUB_URL'])) include './publisher.php';
329function pubsubhub() 234function pubsubhub()
330{ 235{
331 if (!empty($GLOBALS['config']['PUBSUBHUB_URL'])) 236 $conf = ConfigManager::getInstance();
237 $pshUrl = $conf->get('config.PUBSUBHUB_URL');
238 if (!empty($pshUrl))
332 { 239 {
333 $p = new Publisher($GLOBALS['config']['PUBSUBHUB_URL']); 240 include_once './publisher.php';
334 $topic_url = array ( 241 $p = new Publisher($pshUrl);
335 index_url($_SERVER).'?do=atom', 242 $topic_url = array (
336 index_url($_SERVER).'?do=rss' 243 index_url($_SERVER).'?do=atom',
337 ); 244 index_url($_SERVER).'?do=rss'
338 $p->publish_update($topic_url); 245 );
246 $p->publish_update($topic_url);
339 } 247 }
340} 248}
341 249
@@ -345,7 +253,7 @@ function pubsubhub()
345// Returns the IP address of the client (Used to prevent session cookie hijacking.) 253// Returns the IP address of the client (Used to prevent session cookie hijacking.)
346function allIPs() 254function allIPs()
347{ 255{
348 $ip = $_SERVER["REMOTE_ADDR"]; 256 $ip = $_SERVER['REMOTE_ADDR'];
349 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy. 257 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
350 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip=$ip.'_'.$_SERVER['HTTP_X_FORWARDED_FOR']; } 258 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip=$ip.'_'.$_SERVER['HTTP_X_FORWARDED_FOR']; }
351 if (isset($_SERVER['HTTP_CLIENT_IP'])) { $ip=$ip.'_'.$_SERVER['HTTP_CLIENT_IP']; } 259 if (isset($_SERVER['HTTP_CLIENT_IP'])) { $ip=$ip.'_'.$_SERVER['HTTP_CLIENT_IP']; }
@@ -353,23 +261,25 @@ function allIPs()
353} 261}
354 262
355function fillSessionInfo() { 263function fillSessionInfo() {
264 $conf = ConfigManager::getInstance();
356 $_SESSION['uid'] = sha1(uniqid('',true).'_'.mt_rand()); // Generate unique random number (different than phpsessionid) 265 $_SESSION['uid'] = sha1(uniqid('',true).'_'.mt_rand()); // Generate unique random number (different than phpsessionid)
357 $_SESSION['ip']=allIPs(); // We store IP address(es) of the client to make sure session is not hijacked. 266 $_SESSION['ip']=allIPs(); // We store IP address(es) of the client to make sure session is not hijacked.
358 $_SESSION['username']=$GLOBALS['login']; 267 $_SESSION['username']= $conf->get('login');
359 $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // Set session expiration. 268 $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // Set session expiration.
360} 269}
361 270
362// Check that user/password is correct. 271// Check that user/password is correct.
363function check_auth($login,$password) 272function check_auth($login,$password)
364{ 273{
365 $hash = sha1($password.$login.$GLOBALS['salt']); 274 $conf = ConfigManager::getInstance();
366 if ($login==$GLOBALS['login'] && $hash==$GLOBALS['hash']) 275 $hash = sha1($password . $login . $conf->get('salt'));
276 if ($login == $conf->get('login') && $hash == $conf->get('hash'))
367 { // Login/password is correct. 277 { // Login/password is correct.
368 fillSessionInfo(); 278 fillSessionInfo();
369 logm($GLOBALS['config']['LOG_FILE'], $_SERVER['REMOTE_ADDR'], 'Login successful'); 279 logm($conf->get('config.LOG_FILE'), $_SERVER['REMOTE_ADDR'], 'Login successful');
370 return True; 280 return True;
371 } 281 }
372 logm($GLOBALS['config']['LOG_FILE'], $_SERVER['REMOTE_ADDR'], 'Login failed for user '.$login); 282 logm($conf->get('config.LOG_FILE'), $_SERVER['REMOTE_ADDR'], 'Login failed for user '.$login);
373 return False; 283 return False;
374} 284}
375 285
@@ -395,44 +305,64 @@ function logout() {
395// ------------------------------------------------------------------------------------------ 305// ------------------------------------------------------------------------------------------
396// Brute force protection system 306// Brute force protection system
397// Several consecutive failed logins will ban the IP address for 30 minutes. 307// Several consecutive failed logins will ban the IP address for 30 minutes.
398if (!is_file($GLOBALS['config']['IPBANS_FILENAME'])) file_put_contents($GLOBALS['config']['IPBANS_FILENAME'], "<?php\n\$GLOBALS['IPBANS']=".var_export(array('FAILURES'=>array(),'BANS'=>array()),true).";\n?>"); 308if (!is_file($conf->get('config.IPBANS_FILENAME', 'data/ipbans.php'))) {
399include $GLOBALS['config']['IPBANS_FILENAME']; 309 // FIXME! globals
310 file_put_contents(
311 $conf->get('config.IPBANS_FILENAME', 'data/ipbans.php'),
312 "<?php\n\$GLOBALS['IPBANS']=".var_export(array('FAILURES'=>array(),'BANS'=>array()),true).";\n?>"
313 );
314}
315include $conf->get('config.IPBANS_FILENAME', 'data/ipbans.php');
400// Signal a failed login. Will ban the IP if too many failures: 316// Signal a failed login. Will ban the IP if too many failures:
401function ban_loginFailed() 317function ban_loginFailed()
402{ 318{
403 $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS']; 319 $conf = ConfigManager::getInstance();
320 $ip = $_SERVER['REMOTE_ADDR'];
321 $gb = $GLOBALS['IPBANS'];
404 if (!isset($gb['FAILURES'][$ip])) $gb['FAILURES'][$ip]=0; 322 if (!isset($gb['FAILURES'][$ip])) $gb['FAILURES'][$ip]=0;
405 $gb['FAILURES'][$ip]++; 323 $gb['FAILURES'][$ip]++;
406 if ($gb['FAILURES'][$ip]>($GLOBALS['config']['BAN_AFTER']-1)) 324 if ($gb['FAILURES'][$ip] > ($conf->get('config.BAN_AFTER') - 1))
407 { 325 {
408 $gb['BANS'][$ip]=time()+$GLOBALS['config']['BAN_DURATION']; 326 $gb['BANS'][$ip] = time() + $conf->get('config.BAN_DURATION', 1800);
409 logm($GLOBALS['config']['LOG_FILE'], $_SERVER['REMOTE_ADDR'], 'IP address banned from login'); 327 logm($conf->get('config.LOG_FILE'), $_SERVER['REMOTE_ADDR'], 'IP address banned from login');
410 } 328 }
411 $GLOBALS['IPBANS'] = $gb; 329 $GLOBALS['IPBANS'] = $gb;
412 file_put_contents($GLOBALS['config']['IPBANS_FILENAME'], "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>"); 330 file_put_contents(
331 $conf->get('config.IPBANS_FILENAME', 'data/ipbans.php'),
332 "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>"
333 );
413} 334}
414 335
415// Signals a successful login. Resets failed login counter. 336// Signals a successful login. Resets failed login counter.
416function ban_loginOk() 337function ban_loginOk()
417{ 338{
418 $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS']; 339 $conf = ConfigManager::getInstance();
340 $ip = $_SERVER['REMOTE_ADDR'];
341 $gb = $GLOBALS['IPBANS'];
419 unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]); 342 unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]);
420 $GLOBALS['IPBANS'] = $gb; 343 $GLOBALS['IPBANS'] = $gb;
421 file_put_contents($GLOBALS['config']['IPBANS_FILENAME'], "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>"); 344 file_put_contents(
345 $conf->get('config.IPBANS_FILENAME', 'data/ipbans.php'),
346 "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>"
347 );
422} 348}
423 349
424// Checks if the user CAN login. If 'true', the user can try to login. 350// Checks if the user CAN login. If 'true', the user can try to login.
425function ban_canLogin() 351function ban_canLogin()
426{ 352{
353 $conf = ConfigManager::getInstance();
427 $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS']; 354 $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS'];
428 if (isset($gb['BANS'][$ip])) 355 if (isset($gb['BANS'][$ip]))
429 { 356 {
430 // User is banned. Check if the ban has expired: 357 // User is banned. Check if the ban has expired:
431 if ($gb['BANS'][$ip]<=time()) 358 if ($gb['BANS'][$ip]<=time())
432 { // Ban expired, user can try to login again. 359 { // Ban expired, user can try to login again.
433 logm($GLOBALS['config']['LOG_FILE'], $_SERVER['REMOTE_ADDR'], 'Ban lifted.'); 360 logm($conf->get('config.LOG_FILE'), $_SERVER['REMOTE_ADDR'], 'Ban lifted.');
434 unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]); 361 unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]);
435 file_put_contents($GLOBALS['config']['IPBANS_FILENAME'], "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>"); 362 file_put_contents(
363 $conf->get('config.IPBANS_FILENAME', 'data/ipbans.php'),
364 "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>"
365 );
436 return true; // Ban has expired, user can login. 366 return true; // Ban has expired, user can login.
437 } 367 }
438 return false; // User is banned. 368 return false; // User is banned.
@@ -546,7 +476,8 @@ if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are atta
546// Returns a token. 476// Returns a token.
547function getToken() 477function getToken()
548{ 478{
549 $rnd = sha1(uniqid('',true).'_'.mt_rand().$GLOBALS['salt']); // We generate a random string. 479 $conf = ConfigManager::getInstance();
480 $rnd = sha1(uniqid('', true) .'_'. mt_rand() . $conf->get('salt')); // We generate a random string.
550 $_SESSION['tokens'][$rnd]=1; // Store it on the server side. 481 $_SESSION['tokens'][$rnd]=1; // Store it on the server side.
551 return $rnd; 482 return $rnd;
552} 483}
@@ -568,10 +499,11 @@ function tokenOk($token)
568// Gives the last 7 days (which have links). 499// Gives the last 7 days (which have links).
569// This RSS feed cannot be filtered. 500// This RSS feed cannot be filtered.
570function showDailyRSS() { 501function showDailyRSS() {
502 $conf = ConfigManager::getInstance();
571 // Cache system 503 // Cache system
572 $query = $_SERVER['QUERY_STRING']; 504 $query = $_SERVER['QUERY_STRING'];
573 $cache = new CachedPage( 505 $cache = new CachedPage(
574 $GLOBALS['config']['PAGECACHE'], 506 $conf->get('config.PAGE_CACHE'),
575 page_url($_SERVER), 507 page_url($_SERVER),
576 startsWith($query,'do=dailyrss') && !isLoggedIn() 508 startsWith($query,'do=dailyrss') && !isLoggedIn()
577 ); 509 );
@@ -584,11 +516,11 @@ function showDailyRSS() {
584 // If cached was not found (or not usable), then read the database and build the response: 516 // If cached was not found (or not usable), then read the database and build the response:
585 // Read links from database (and filter private links if used it not logged in). 517 // Read links from database (and filter private links if used it not logged in).
586 $LINKSDB = new LinkDB( 518 $LINKSDB = new LinkDB(
587 $GLOBALS['config']['DATASTORE'], 519 $conf->get('config.DATASTORE'),
588 isLoggedIn(), 520 isLoggedIn(),
589 $GLOBALS['config']['HIDE_PUBLIC_LINKS'], 521 $conf->get('config.HIDE_PUBLIC_LINKS'),
590 $GLOBALS['redirector'], 522 $conf->get('redirector'),
591 $GLOBALS['config']['REDIRECTOR_URLENCODE'] 523 $conf->get('config.REDIRECTOR_URLENCODE')
592 ); 524 );
593 525
594 /* Some Shaarlies may have very few links, so we need to look 526 /* Some Shaarlies may have very few links, so we need to look
@@ -600,7 +532,7 @@ function showDailyRSS() {
600 } 532 }
601 rsort($linkdates); 533 rsort($linkdates);
602 $nb_of_days = 7; // We take 7 days. 534 $nb_of_days = 7; // We take 7 days.
603 $today = Date('Ymd'); 535 $today = date('Ymd');
604 $days = array(); 536 $days = array();
605 537
606 foreach ($linkdates as $linkdate) { 538 foreach ($linkdates as $linkdate) {
@@ -622,7 +554,7 @@ function showDailyRSS() {
622 $pageaddr = escape(index_url($_SERVER)); 554 $pageaddr = escape(index_url($_SERVER));
623 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">'; 555 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">';
624 echo '<channel>'; 556 echo '<channel>';
625 echo '<title>Daily - '. $GLOBALS['title'] . '</title>'; 557 echo '<title>Daily - '. $conf->get('title') . '</title>';
626 echo '<link>'. $pageaddr .'</link>'; 558 echo '<link>'. $pageaddr .'</link>';
627 echo '<description>Daily shared links</description>'; 559 echo '<description>Daily shared links</description>';
628 echo '<language>en-en</language>'; 560 echo '<language>en-en</language>';
@@ -641,7 +573,7 @@ function showDailyRSS() {
641 // We pre-format some fields for proper output. 573 // We pre-format some fields for proper output.
642 foreach ($linkdates as $linkdate) { 574 foreach ($linkdates as $linkdate) {
643 $l = $LINKSDB[$linkdate]; 575 $l = $LINKSDB[$linkdate];
644 $l['formatedDescription'] = format_description($l['description'], $GLOBALS['redirector']); 576 $l['formatedDescription'] = format_description($l['description'], $conf->get('redirector'));
645 $l['thumbnail'] = thumbnail($l['url']); 577 $l['thumbnail'] = thumbnail($l['url']);
646 $l_date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $l['linkdate']); 578 $l_date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $l['linkdate']);
647 $l['timestamp'] = $l_date->getTimestamp(); 579 $l['timestamp'] = $l_date->getTimestamp();
@@ -653,7 +585,7 @@ function showDailyRSS() {
653 585
654 // Then build the HTML for this day: 586 // Then build the HTML for this day:
655 $tpl = new RainTPL; 587 $tpl = new RainTPL;
656 $tpl->assign('title', $GLOBALS['title']); 588 $tpl->assign('title', $conf->get('title'));
657 $tpl->assign('daydate', $dayDate->getTimestamp()); 589 $tpl->assign('daydate', $dayDate->getTimestamp());
658 $tpl->assign('absurl', $absurl); 590 $tpl->assign('absurl', $absurl);
659 $tpl->assign('links', $links); 591 $tpl->assign('links', $links);
@@ -677,7 +609,8 @@ function showDailyRSS() {
677 */ 609 */
678function showDaily($pageBuilder, $LINKSDB) 610function showDaily($pageBuilder, $LINKSDB)
679{ 611{
680 $day=Date('Ymd',strtotime('-1 day')); // Yesterday, in format YYYYMMDD. 612 $conf = ConfigManager::getInstance();
613 $day=date('Ymd',strtotime('-1 day')); // Yesterday, in format YYYYMMDD.
681 if (isset($_GET['day'])) $day=$_GET['day']; 614 if (isset($_GET['day'])) $day=$_GET['day'];
682 615
683 $days = $LINKSDB->days(); 616 $days = $LINKSDB->days();
@@ -705,7 +638,7 @@ function showDaily($pageBuilder, $LINKSDB)
705 $taglist = explode(' ',$link['tags']); 638 $taglist = explode(' ',$link['tags']);
706 uasort($taglist, 'strcasecmp'); 639 uasort($taglist, 'strcasecmp');
707 $linksToDisplay[$key]['taglist']=$taglist; 640 $linksToDisplay[$key]['taglist']=$taglist;
708 $linksToDisplay[$key]['formatedDescription'] = format_description($link['description'], $GLOBALS['redirector']); 641 $linksToDisplay[$key]['formatedDescription'] = format_description($link['description'], $conf->get('redirector'));
709 $linksToDisplay[$key]['thumbnail'] = thumbnail($link['url']); 642 $linksToDisplay[$key]['thumbnail'] = thumbnail($link['url']);
710 $date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $link['linkdate']); 643 $date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $link['linkdate']);
711 $linksToDisplay[$key]['timestamp'] = $date->getTimestamp(); 644 $linksToDisplay[$key]['timestamp'] = $date->getTimestamp();
@@ -763,17 +696,17 @@ function showLinkList($PAGE, $LINKSDB) {
763// Render HTML page (according to URL parameters and user rights) 696// Render HTML page (according to URL parameters and user rights)
764function renderPage() 697function renderPage()
765{ 698{
699 $conf = ConfigManager::getInstance();
766 $LINKSDB = new LinkDB( 700 $LINKSDB = new LinkDB(
767 $GLOBALS['config']['DATASTORE'], 701 $conf->get('config.DATASTORE'),
768 isLoggedIn(), 702 isLoggedIn(),
769 $GLOBALS['config']['HIDE_PUBLIC_LINKS'], 703 $conf->get('config.HIDE_PUBLIC_LINKS'),
770 $GLOBALS['redirector'], 704 $conf->get('redirector'),
771 $GLOBALS['config']['REDIRECTOR_URLENCODE'] 705 $conf->get('config.REDIRECTOR_URLENCODE')
772 ); 706 );
773 707
774 $updater = new Updater( 708 $updater = new Updater(
775 read_updates_file($GLOBALS['config']['UPDATES_FILE']), 709 read_updates_file($conf->get('config.UPDATES_FILE')),
776 $GLOBALS,
777 $LINKSDB, 710 $LINKSDB,
778 isLoggedIn() 711 isLoggedIn()
779 ); 712 );
@@ -781,7 +714,7 @@ function renderPage()
781 $newUpdates = $updater->update(); 714 $newUpdates = $updater->update();
782 if (! empty($newUpdates)) { 715 if (! empty($newUpdates)) {
783 write_updates_file( 716 write_updates_file(
784 $GLOBALS['config']['UPDATES_FILE'], 717 $conf->get('config.UPDATES_FILE'),
785 $updater->getDoneUpdates() 718 $updater->getDoneUpdates()
786 ); 719 );
787 } 720 }
@@ -820,7 +753,7 @@ function renderPage()
820 // -------- Display login form. 753 // -------- Display login form.
821 if ($targetPage == Router::$PAGE_LOGIN) 754 if ($targetPage == Router::$PAGE_LOGIN)
822 { 755 {
823 if ($GLOBALS['config']['OPEN_SHAARLI']) { header('Location: ?'); exit; } // No need to login for open Shaarli 756 if ($conf->get('config.OPEN_SHAARLI')) { header('Location: ?'); exit; } // No need to login for open Shaarli
824 $token=''; if (ban_canLogin()) $token=getToken(); // Do not waste token generation if not useful. 757 $token=''; if (ban_canLogin()) $token=getToken(); // Do not waste token generation if not useful.
825 $PAGE->assign('token',$token); 758 $PAGE->assign('token',$token);
826 if (isset($_GET['username'])) { 759 if (isset($_GET['username'])) {
@@ -833,7 +766,7 @@ function renderPage()
833 // -------- User wants to logout. 766 // -------- User wants to logout.
834 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout')) 767 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout'))
835 { 768 {
836 invalidateCaches($GLOBALS['config']['PAGECACHE']); 769 invalidateCaches($conf->get('config.PAGECACHE'));
837 logout(); 770 logout();
838 header('Location: ?'); 771 header('Location: ?');
839 exit; 772 exit;
@@ -933,7 +866,7 @@ function renderPage()
933 // Cache system 866 // Cache system
934 $query = $_SERVER['QUERY_STRING']; 867 $query = $_SERVER['QUERY_STRING'];
935 $cache = new CachedPage( 868 $cache = new CachedPage(
936 $GLOBALS['config']['PAGECACHE'], 869 $conf->get('config.PAGECACHE'),
937 page_url($_SERVER), 870 page_url($_SERVER),
938 startsWith($query,'do='. $targetPage) && !isLoggedIn() 871 startsWith($query,'do='. $targetPage) && !isLoggedIn()
939 ); 872 );
@@ -946,10 +879,11 @@ function renderPage()
946 // Generate data. 879 // Generate data.
947 $feedGenerator = new FeedBuilder($LINKSDB, $feedType, $_SERVER, $_GET, isLoggedIn()); 880 $feedGenerator = new FeedBuilder($LINKSDB, $feedType, $_SERVER, $_GET, isLoggedIn());
948 $feedGenerator->setLocale(strtolower(setlocale(LC_COLLATE, 0))); 881 $feedGenerator->setLocale(strtolower(setlocale(LC_COLLATE, 0)));
949 $feedGenerator->setHideDates($GLOBALS['config']['HIDE_TIMESTAMPS'] && !isLoggedIn()); 882 $feedGenerator->setHideDates($conf->get('config.HIDE_TIMESTAMPS') && !isLoggedIn());
950 $feedGenerator->setUsePermalinks(isset($_GET['permalinks']) || !$GLOBALS['config']['ENABLE_RSS_PERMALINKS']); 883 $feedGenerator->setUsePermalinks(isset($_GET['permalinks']) || !$conf->get('config.ENABLE_RSS_PERMALINKS'));
951 if (!empty($GLOBALS['config']['PUBSUBHUB_URL'])) { 884 $pshUrl = $conf->get('config.PUBSUBHUB_URL');
952 $feedGenerator->setPubsubhubUrl($GLOBALS['config']['PUBSUBHUB_URL']); 885 if (!empty($pshUrl)) {
886 $feedGenerator->setPubsubhubUrl($pshUrl);
953 } 887 }
954 $data = $feedGenerator->buildData(); 888 $data = $feedGenerator->buildData();
955 889
@@ -1110,19 +1044,23 @@ function renderPage()
1110 // -------- User wants to change his/her password. 1044 // -------- User wants to change his/her password.
1111 if ($targetPage == Router::$PAGE_CHANGEPASSWORD) 1045 if ($targetPage == Router::$PAGE_CHANGEPASSWORD)
1112 { 1046 {
1113 if ($GLOBALS['config']['OPEN_SHAARLI']) die('You are not supposed to change a password on an Open Shaarli.'); 1047 if ($conf->get('config.OPEN_SHAARLI')) {
1048 die('You are not supposed to change a password on an Open Shaarli.');
1049 }
1050
1114 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword'])) 1051 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword']))
1115 { 1052 {
1116 if (!tokenOk($_POST['token'])) die('Wrong token.'); // Go away! 1053 if (!tokenOk($_POST['token'])) die('Wrong token.'); // Go away!
1117 1054
1118 // Make sure old password is correct. 1055 // Make sure old password is correct.
1119 $oldhash = sha1($_POST['oldpassword'].$GLOBALS['login'].$GLOBALS['salt']); 1056 $oldhash = sha1($_POST['oldpassword'].$conf->get('login').$conf->get('salt'));
1120 if ($oldhash!=$GLOBALS['hash']) { echo '<script>alert("The old password is not correct.");document.location=\'?do=changepasswd\';</script>'; exit; } 1057 if ($oldhash!= $conf->get('hash')) { echo '<script>alert("The old password is not correct.");document.location=\'?do=changepasswd\';</script>'; exit; }
1121 // Save new password 1058 // Save new password
1122 $GLOBALS['salt'] = sha1(uniqid('',true).'_'.mt_rand()); // Salt renders rainbow-tables attacks useless. 1059 // Salt renders rainbow-tables attacks useless.
1123 $GLOBALS['hash'] = sha1($_POST['setpassword'].$GLOBALS['login'].$GLOBALS['salt']); 1060 $conf->set('salt', sha1(uniqid('', true) .'_'. mt_rand()));
1061 $conf->set('hash', sha1($_POST['setpassword'] . $conf->get('login') . $conf->get('salt')));
1124 try { 1062 try {
1125 writeConfig($GLOBALS, isLoggedIn()); 1063 $conf->write(isLoggedIn());
1126 } 1064 }
1127 catch(Exception $e) { 1065 catch(Exception $e) {
1128 error_log( 1066 error_log(
@@ -1159,17 +1097,17 @@ function renderPage()
1159 ) { 1097 ) {
1160 $tz = $_POST['continent'] . '/' . $_POST['city']; 1098 $tz = $_POST['continent'] . '/' . $_POST['city'];
1161 } 1099 }
1162 $GLOBALS['timezone'] = $tz; 1100 $conf->set('timezone', $tz);
1163 $GLOBALS['title']=$_POST['title']; 1101 $conf->set('title', $_POST['title']);
1164 $GLOBALS['titleLink']=$_POST['titleLink']; 1102 $conf->set('titleLink', $_POST['titleLink']);
1165 $GLOBALS['redirector']=$_POST['redirector']; 1103 $conf->set('redirector', $_POST['redirector']);
1166 $GLOBALS['disablesessionprotection']=!empty($_POST['disablesessionprotection']); 1104 $conf->set('disablesessionprotection', !empty($_POST['disablesessionprotection']));
1167 $GLOBALS['privateLinkByDefault']=!empty($_POST['privateLinkByDefault']); 1105 $conf->set('privateLinkByDefault', !empty($_POST['privateLinkByDefault']));
1168 $GLOBALS['config']['ENABLE_RSS_PERMALINKS']= !empty($_POST['enableRssPermalinks']); 1106 $conf->set('config.ENABLE_RSS_PERMALINKS', !empty($_POST['enableRssPermalinks']));
1169 $GLOBALS['config']['ENABLE_UPDATECHECK'] = !empty($_POST['updateCheck']); 1107 $conf->set('config.ENABLE_UPDATECHECK', !empty($_POST['updateCheck']));
1170 $GLOBALS['config']['HIDE_PUBLIC_LINKS'] = !empty($_POST['hidePublicLinks']); 1108 $conf->set('config.HIDE_PUBLIC_LINKS', !empty($_POST['hidePublicLinks']));
1171 try { 1109 try {
1172 writeConfig($GLOBALS, isLoggedIn()); 1110 $conf->write(isLoggedIn());
1173 } 1111 }
1174 catch(Exception $e) { 1112 catch(Exception $e) {
1175 error_log( 1113 error_log(
@@ -1178,20 +1116,24 @@ function renderPage()
1178 ); 1116 );
1179 1117
1180 // TODO: do not handle exceptions/errors in JS. 1118 // TODO: do not handle exceptions/errors in JS.
1181 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=tools\';</script>'; 1119 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=configure\';</script>';
1182 exit; 1120 exit;
1183 } 1121 }
1184 echo '<script>alert("Configuration was saved.");document.location=\'?do=tools\';</script>'; 1122 echo '<script>alert("Configuration was saved.");document.location=\'?do=configure\';</script>';
1185 exit; 1123 exit;
1186 } 1124 }
1187 else // Show the configuration form. 1125 else // Show the configuration form.
1188 { 1126 {
1189 $PAGE->assign('token',getToken()); 1127 $PAGE->assign('token',getToken());
1190 $PAGE->assign('title', empty($GLOBALS['title']) ? '' : $GLOBALS['title'] ); 1128 $PAGE->assign('title', $conf->get('title'));
1191 $PAGE->assign('redirector', empty($GLOBALS['redirector']) ? '' : $GLOBALS['redirector'] ); 1129 $PAGE->assign('redirector', $conf->get('redirector'));
1192 list($timezone_form, $timezone_js) = generateTimeZoneForm($GLOBALS['timezone']); 1130 list($timezone_form, $timezone_js) = generateTimeZoneForm($conf->get('timezone'));
1193 $PAGE->assign('timezone_form', $timezone_form); 1131 $PAGE->assign('timezone_form', $timezone_form);
1194 $PAGE->assign('timezone_js',$timezone_js); 1132 $PAGE->assign('timezone_js',$timezone_js);
1133 $PAGE->assign('private_links_default', $conf->get('privateLinkByDefault'));
1134 $PAGE->assign('enable_rss_permalinks', $conf->get('config.ENABLE_RSS_PERMALINKS'));
1135 $PAGE->assign('enable_update_check', $conf->get('config.ENABLE_UPDATECHECK'));
1136 $PAGE->assign('hide_public_links', $conf->get('config.HIDE_PUBLIC_LINKS'));
1195 $PAGE->renderPage('configure'); 1137 $PAGE->renderPage('configure');
1196 exit; 1138 exit;
1197 } 1139 }
@@ -1223,7 +1165,7 @@ function renderPage()
1223 $value['tags']=trim(implode(' ',$tags)); 1165 $value['tags']=trim(implode(' ',$tags));
1224 $LINKSDB[$key]=$value; 1166 $LINKSDB[$key]=$value;
1225 } 1167 }
1226 $LINKSDB->savedb($GLOBALS['config']['PAGECACHE']); 1168 $LINKSDB->savedb($conf->get('config.PAGECACHE'));
1227 echo '<script>alert("Tag was removed from '.count($linksToAlter).' links.");document.location=\'?\';</script>'; 1169 echo '<script>alert("Tag was removed from '.count($linksToAlter).' links.");document.location=\'?\';</script>';
1228 exit; 1170 exit;
1229 } 1171 }
@@ -1240,7 +1182,7 @@ function renderPage()
1240 $value['tags']=trim(implode(' ',$tags)); 1182 $value['tags']=trim(implode(' ',$tags));
1241 $LINKSDB[$key]=$value; 1183 $LINKSDB[$key]=$value;
1242 } 1184 }
1243 $LINKSDB->savedb($GLOBALS['config']['PAGECACHE']); // Save to disk. 1185 $LINKSDB->savedb($conf->get('config.PAGECACHE')); // Save to disk.
1244 echo '<script>alert("Tag was renamed in '.count($linksToAlter).' links.");document.location=\'?searchtags='.urlencode($_POST['totag']).'\';</script>'; 1186 echo '<script>alert("Tag was renamed in '.count($linksToAlter).' links.");document.location=\'?searchtags='.urlencode($_POST['totag']).'\';</script>';
1245 exit; 1187 exit;
1246 } 1188 }
@@ -1291,7 +1233,7 @@ function renderPage()
1291 $pluginManager->executeHooks('save_link', $link); 1233 $pluginManager->executeHooks('save_link', $link);
1292 1234
1293 $LINKSDB[$linkdate] = $link; 1235 $LINKSDB[$linkdate] = $link;
1294 $LINKSDB->savedb($GLOBALS['config']['PAGECACHE']); 1236 $LINKSDB->savedb($conf->get('config.PAGECACHE'));
1295 pubsubhub(); 1237 pubsubhub();
1296 1238
1297 // If we are called from the bookmarklet, we must close the popup: 1239 // If we are called from the bookmarklet, we must close the popup:
@@ -1333,7 +1275,7 @@ function renderPage()
1333 $pluginManager->executeHooks('delete_link', $LINKSDB[$linkdate]); 1275 $pluginManager->executeHooks('delete_link', $LINKSDB[$linkdate]);
1334 1276
1335 unset($LINKSDB[$linkdate]); 1277 unset($LINKSDB[$linkdate]);
1336 $LINKSDB->savedb($GLOBALS['config']['PAGECACHE']); // save to disk 1278 $LINKSDB->savedb('config.PAGECACHE'); // save to disk
1337 1279
1338 // If we are called from the bookmarklet, we must close the popup: 1280 // If we are called from the bookmarklet, we must close the popup:
1339 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; } 1281 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
@@ -1533,7 +1475,7 @@ function renderPage()
1533 // Split plugins into 2 arrays: ordered enabled plugins and disabled. 1475 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1534 $enabledPlugins = array_filter($pluginMeta, function($v) { return $v['order'] !== false; }); 1476 $enabledPlugins = array_filter($pluginMeta, function($v) { return $v['order'] !== false; });
1535 // Load parameters. 1477 // Load parameters.
1536 $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $GLOBALS['plugins']); 1478 $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array()));
1537 uasort( 1479 uasort(
1538 $enabledPlugins, 1480 $enabledPlugins,
1539 function($a, $b) { return $a['order'] - $b['order']; } 1481 function($a, $b) { return $a['order'] - $b['order']; }
@@ -1552,13 +1494,13 @@ function renderPage()
1552 if (isset($_POST['parameters_form'])) { 1494 if (isset($_POST['parameters_form'])) {
1553 unset($_POST['parameters_form']); 1495 unset($_POST['parameters_form']);
1554 foreach ($_POST as $param => $value) { 1496 foreach ($_POST as $param => $value) {
1555 $GLOBALS['plugins'][$param] = escape($value); 1497 $conf->set('plugins.'. $param, escape($value));
1556 } 1498 }
1557 } 1499 }
1558 else { 1500 else {
1559 $GLOBALS['config']['ENABLED_PLUGINS'] = save_plugin_config($_POST); 1501 $conf->set('config.ENABLED_PLUGINS', save_plugin_config($_POST));
1560 } 1502 }
1561 writeConfig($GLOBALS, isLoggedIn()); 1503 $conf->write(isLoggedIn());
1562 } 1504 }
1563 catch (Exception $e) { 1505 catch (Exception $e) {
1564 error_log( 1506 error_log(
@@ -1584,6 +1526,7 @@ function renderPage()
1584function importFile($LINKSDB) 1526function importFile($LINKSDB)
1585{ 1527{
1586 if (!isLoggedIn()) { die('Not allowed.'); } 1528 if (!isLoggedIn()) { die('Not allowed.'); }
1529 $conf = ConfigManager::getInstance();
1587 1530
1588 $filename=$_FILES['filetoupload']['name']; 1531 $filename=$_FILES['filetoupload']['name'];
1589 $filesize=$_FILES['filetoupload']['size']; 1532 $filesize=$_FILES['filetoupload']['size'];
@@ -1654,7 +1597,7 @@ function importFile($LINKSDB)
1654 } 1597 }
1655 } 1598 }
1656 } 1599 }
1657 $LINKSDB->savedb($GLOBALS['config']['PAGECACHE']); 1600 $LINKSDB->savedb($conf->get('config.PAGECACHE'));
1658 1601
1659 echo '<script>alert("File '.json_encode($filename).' ('.$filesize.' bytes) was successfully processed: '.$import_count.' links imported.");document.location=\'?\';</script>'; 1602 echo '<script>alert("File '.json_encode($filename).' ('.$filesize.' bytes) was successfully processed: '.$import_count.' links imported.");document.location=\'?\';</script>';
1660 } 1603 }
@@ -1673,6 +1616,7 @@ function importFile($LINKSDB)
1673 */ 1616 */
1674function buildLinkList($PAGE,$LINKSDB) 1617function buildLinkList($PAGE,$LINKSDB)
1675{ 1618{
1619 $conf = ConfigManager::getInstance();
1676 // Used in templates 1620 // Used in templates
1677 $searchtags = !empty($_GET['searchtags']) ? escape($_GET['searchtags']) : ''; 1621 $searchtags = !empty($_GET['searchtags']) ? escape($_GET['searchtags']) : '';
1678 $searchterm = !empty($_GET['searchterm']) ? escape($_GET['searchterm']) : ''; 1622 $searchterm = !empty($_GET['searchterm']) ? escape($_GET['searchterm']) : '';
@@ -1700,7 +1644,7 @@ function buildLinkList($PAGE,$LINKSDB)
1700 1644
1701 // If there is only a single link, we change on-the-fly the title of the page. 1645 // If there is only a single link, we change on-the-fly the title of the page.
1702 if (count($linksToDisplay) == 1) { 1646 if (count($linksToDisplay) == 1) {
1703 $GLOBALS['pagetitle'] = $linksToDisplay[$keys[0]]['title'].' - '.$GLOBALS['title']; 1647 $conf->set('pagetitle', $linksToDisplay[$keys[0]]['title'] .' - '. $conf->get('title'));
1704 } 1648 }
1705 1649
1706 // Select articles according to paging. 1650 // Select articles according to paging.
@@ -1716,7 +1660,7 @@ function buildLinkList($PAGE,$LINKSDB)
1716 while ($i<$end && $i<count($keys)) 1660 while ($i<$end && $i<count($keys))
1717 { 1661 {
1718 $link = $linksToDisplay[$keys[$i]]; 1662 $link = $linksToDisplay[$keys[$i]];
1719 $link['description'] = format_description($link['description'], $GLOBALS['redirector']); 1663 $link['description'] = format_description($link['description'], $conf->get('redirector'));
1720 $classLi = ($i % 2) != 0 ? '' : 'publicLinkHightLight'; 1664 $classLi = ($i % 2) != 0 ? '' : 'publicLinkHightLight';
1721 $link['class'] = $link['private'] == 0 ? $classLi : 'private'; 1665 $link['class'] = $link['private'] == 0 ? $classLi : 'private';
1722 $date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $link['linkdate']); 1666 $date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $link['linkdate']);
@@ -1758,14 +1702,14 @@ function buildLinkList($PAGE,$LINKSDB)
1758 'result_count' => count($linksToDisplay), 1702 'result_count' => count($linksToDisplay),
1759 'search_term' => $searchterm, 1703 'search_term' => $searchterm,
1760 'search_tags' => $searchtags, 1704 'search_tags' => $searchtags,
1761 'redirector' => empty($GLOBALS['redirector']) ? '' : $GLOBALS['redirector'], // Optional redirector URL. 1705 'redirector' => $conf->get('redirector'), // Optional redirector URL.
1762 'token' => $token, 1706 'token' => $token,
1763 'links' => $linkDisp, 1707 'links' => $linkDisp,
1764 'tags' => $LINKSDB->allTags(), 1708 'tags' => $LINKSDB->allTags(),
1765 ); 1709 );
1766 // FIXME! temporary fix - see #399. 1710 // FIXME! temporary fix - see #399.
1767 if (!empty($GLOBALS['pagetitle']) && count($linkDisp) == 1) { 1711 if ($conf->exists('pagetitle') && count($linkDisp) == 1) {
1768 $data['pagetitle'] = $GLOBALS['pagetitle']; 1712 $data['pagetitle'] = $conf->get('pagetitle');
1769 } 1713 }
1770 1714
1771 $pluginManager = PluginManager::getInstance(); 1715 $pluginManager = PluginManager::getInstance();
@@ -1789,7 +1733,8 @@ function buildLinkList($PAGE,$LINKSDB)
1789// Return an empty array if no thumbnail available. 1733// Return an empty array if no thumbnail available.
1790function computeThumbnail($url,$href=false) 1734function computeThumbnail($url,$href=false)
1791{ 1735{
1792 if (!$GLOBALS['config']['ENABLE_THUMBNAILS']) return array(); 1736 $conf = ConfigManager::getInstance();
1737 if (!$conf->get('config.ENABLE_THUMBNAILS')) return array();
1793 if ($href==false) $href=$url; 1738 if ($href==false) $href=$url;
1794 1739
1795 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link. 1740 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
@@ -1857,7 +1802,7 @@ function computeThumbnail($url,$href=false)
1857 // So we deport the thumbnail generation in order not to slow down page generation 1802 // So we deport the thumbnail generation in order not to slow down page generation
1858 // (and we also cache the thumbnail) 1803 // (and we also cache the thumbnail)
1859 1804
1860 if (!$GLOBALS['config']['ENABLE_LOCALCACHE']) return array(); // If local cache is disabled, no thumbnails for services which require the use a local cache. 1805 if (! $conf->get('config.ENABLE_LOCALCACHE')) return array(); // If local cache is disabled, no thumbnails for services which require the use a local cache.
1861 1806
1862 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com') 1807 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com')
1863 || $domain=='vimeo.com' 1808 || $domain=='vimeo.com'
@@ -1880,7 +1825,7 @@ function computeThumbnail($url,$href=false)
1880 $path = parse_url($url,PHP_URL_PATH); 1825 $path = parse_url($url,PHP_URL_PATH);
1881 if ("/talks/" !== substr($path,0,7)) return array(); // This is not a single video URL. 1826 if ("/talks/" !== substr($path,0,7)) return array(); // This is not a single video URL.
1882 } 1827 }
1883 $sign = hash_hmac('sha256', $url, $GLOBALS['salt']); // We use the salt to sign data (it's random, secret, and specific to each installation) 1828 $sign = hash_hmac('sha256', $url, $conf->get('salt')); // We use the salt to sign data (it's random, secret, and specific to each installation)
1884 return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url), 1829 return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url),
1885 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail'); 1830 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail');
1886 } 1831 }
@@ -1891,7 +1836,7 @@ function computeThumbnail($url,$href=false)
1891 $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION)); 1836 $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION));
1892 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif') 1837 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
1893 { 1838 {
1894 $sign = hash_hmac('sha256', $url, $GLOBALS['salt']); // We use the salt to sign data (it's random, secret, and specific to each installation) 1839 $sign = hash_hmac('sha256', $url, $conf->get('salt')); // We use the salt to sign data (it's random, secret, and specific to each installation)
1895 return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url), 1840 return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url),
1896 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail'); 1841 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail');
1897 } 1842 }
@@ -1988,21 +1933,28 @@ function install()
1988 1933
1989 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword'])) 1934 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword']))
1990 { 1935 {
1936 $conf = ConfigManager::getInstance();
1991 $tz = 'UTC'; 1937 $tz = 'UTC';
1992 if (!empty($_POST['continent']) && !empty($_POST['city']) 1938 if (!empty($_POST['continent']) && !empty($_POST['city'])
1993 && isTimeZoneValid($_POST['continent'], $_POST['city']) 1939 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1994 ) { 1940 ) {
1995 $tz = $_POST['continent'].'/'.$_POST['city']; 1941 $tz = $_POST['continent'].'/'.$_POST['city'];
1996 } 1942 }
1997 $GLOBALS['timezone'] = $tz; 1943 $conf->set('timezone', $tz);
1998 // Everything is ok, let's create config file. 1944 $login = $_POST['setlogin'];
1999 $GLOBALS['login'] = $_POST['setlogin']; 1945 $conf->set('login', $login);
2000 $GLOBALS['salt'] = sha1(uniqid('',true).'_'.mt_rand()); // Salt renders rainbow-tables attacks useless. 1946 $salt = sha1(uniqid('', true) .'_'. mt_rand());
2001 $GLOBALS['hash'] = sha1($_POST['setpassword'].$GLOBALS['login'].$GLOBALS['salt']); 1947 $conf->set('salt', $salt);
2002 $GLOBALS['title'] = (empty($_POST['title']) ? 'Shared links on '.escape(index_url($_SERVER)) : $_POST['title'] ); 1948 $conf->set('hash', sha1($_POST['setpassword'] . $login . $salt));
2003 $GLOBALS['config']['ENABLE_UPDATECHECK'] = !empty($_POST['updateCheck']); 1949 if (!empty($_POST['title'])) {
1950 $conf->set('title', $_POST['title']);
1951 } else {
1952 $conf->set('title', 'Shared links on '.escape(index_url($_SERVER)));
1953 }
1954 $conf->set('config.ENABLE_UPDATECHECK', !empty($_POST['updateCheck']));
2004 try { 1955 try {
2005 writeConfig($GLOBALS, isLoggedIn()); 1956 // Everything is ok, let's create config file.
1957 $conf->write(isLoggedIn());
2006 } 1958 }
2007 catch(Exception $e) { 1959 catch(Exception $e) {
2008 error_log( 1960 error_log(
@@ -2043,24 +1995,26 @@ function install()
2043*/ 1995*/
2044function genThumbnail() 1996function genThumbnail()
2045{ 1997{
1998 $conf = ConfigManager::getInstance();
2046 // Make sure the parameters in the URL were generated by us. 1999 // Make sure the parameters in the URL were generated by us.
2047 $sign = hash_hmac('sha256', $_GET['url'], $GLOBALS['salt']); 2000 $sign = hash_hmac('sha256', $_GET['url'], $conf->get('salt'));
2048 if ($sign!=$_GET['hmac']) die('Naughty boy!'); 2001 if ($sign!=$_GET['hmac']) die('Naughty boy!');
2049 2002
2003 $cacheDir = $conf->get('config.CACHEDIR', 'cache');
2050 // Let's see if we don't already have the image for this URL in the cache. 2004 // Let's see if we don't already have the image for this URL in the cache.
2051 $thumbname=hash('sha1',$_GET['url']).'.jpg'; 2005 $thumbname=hash('sha1',$_GET['url']).'.jpg';
2052 if (is_file($GLOBALS['config']['CACHEDIR'].'/'.$thumbname)) 2006 if (is_file($cacheDir .'/'. $thumbname))
2053 { // We have the thumbnail, just serve it: 2007 { // We have the thumbnail, just serve it:
2054 header('Content-Type: image/jpeg'); 2008 header('Content-Type: image/jpeg');
2055 echo file_get_contents($GLOBALS['config']['CACHEDIR'].'/'.$thumbname); 2009 echo file_get_contents($cacheDir .'/'. $thumbname);
2056 return; 2010 return;
2057 } 2011 }
2058 // We may also serve a blank image (if service did not respond) 2012 // We may also serve a blank image (if service did not respond)
2059 $blankname=hash('sha1',$_GET['url']).'.gif'; 2013 $blankname=hash('sha1',$_GET['url']).'.gif';
2060 if (is_file($GLOBALS['config']['CACHEDIR'].'/'.$blankname)) 2014 if (is_file($cacheDir .'/'. $blankname))
2061 { 2015 {
2062 header('Content-Type: image/gif'); 2016 header('Content-Type: image/gif');
2063 echo file_get_contents($GLOBALS['config']['CACHEDIR'].'/'.$blankname); 2017 echo file_get_contents($cacheDir .'/'. $blankname);
2064 return; 2018 return;
2065 } 2019 }
2066 2020
@@ -2107,7 +2061,7 @@ function genThumbnail()
2107 list($headers, $content) = get_http_response($imageurl, 10); 2061 list($headers, $content) = get_http_response($imageurl, 10);
2108 if (strpos($headers[0], '200 OK') !== false) { 2062 if (strpos($headers[0], '200 OK') !== false) {
2109 // Save image to cache. 2063 // Save image to cache.
2110 file_put_contents($GLOBALS['config']['CACHEDIR'].'/' . $thumbname, $content); 2064 file_put_contents($cacheDir .'/'. $thumbname, $content);
2111 header('Content-Type: image/jpeg'); 2065 header('Content-Type: image/jpeg');
2112 echo $content; 2066 echo $content;
2113 return; 2067 return;
@@ -2128,7 +2082,7 @@ function genThumbnail()
2128 list($headers, $content) = get_http_response($imageurl, 10); 2082 list($headers, $content) = get_http_response($imageurl, 10);
2129 if (strpos($headers[0], '200 OK') !== false) { 2083 if (strpos($headers[0], '200 OK') !== false) {
2130 // Save image to cache. 2084 // Save image to cache.
2131 file_put_contents($GLOBALS['config']['CACHEDIR'] . '/' . $thumbname, $content); 2085 file_put_contents($cacheDir .'/'. $thumbname, $content);
2132 header('Content-Type: image/jpeg'); 2086 header('Content-Type: image/jpeg');
2133 echo $content; 2087 echo $content;
2134 return; 2088 return;
@@ -2151,7 +2105,7 @@ function genThumbnail()
2151 // No control on image size, so wait long enough 2105 // No control on image size, so wait long enough
2152 list($headers, $content) = get_http_response($imageurl, 20); 2106 list($headers, $content) = get_http_response($imageurl, 20);
2153 if (strpos($headers[0], '200 OK') !== false) { 2107 if (strpos($headers[0], '200 OK') !== false) {
2154 $filepath=$GLOBALS['config']['CACHEDIR'].'/'.$thumbname; 2108 $filepath = $cacheDir .'/'. $thumbname;
2155 file_put_contents($filepath, $content); // Save image to cache. 2109 file_put_contents($filepath, $content); // Save image to cache.
2156 if (resizeImage($filepath)) 2110 if (resizeImage($filepath))
2157 { 2111 {
@@ -2179,7 +2133,7 @@ function genThumbnail()
2179 // No control on image size, so wait long enough 2133 // No control on image size, so wait long enough
2180 list($headers, $content) = get_http_response($imageurl, 20); 2134 list($headers, $content) = get_http_response($imageurl, 20);
2181 if (strpos($headers[0], '200 OK') !== false) { 2135 if (strpos($headers[0], '200 OK') !== false) {
2182 $filepath=$GLOBALS['config']['CACHEDIR'].'/'.$thumbname; 2136 $filepath = $cacheDir.'/'.$thumbname;
2183 // Save image to cache. 2137 // Save image to cache.
2184 file_put_contents($filepath, $content); 2138 file_put_contents($filepath, $content);
2185 if (resizeImage($filepath)) 2139 if (resizeImage($filepath))
@@ -2199,7 +2153,7 @@ function genThumbnail()
2199 // We allow 30 seconds max to download (and downloads are limited to 4 Mb) 2153 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
2200 list($headers, $content) = get_http_response($url, 30); 2154 list($headers, $content) = get_http_response($url, 30);
2201 if (strpos($headers[0], '200 OK') !== false) { 2155 if (strpos($headers[0], '200 OK') !== false) {
2202 $filepath=$GLOBALS['config']['CACHEDIR'].'/'.$thumbname; 2156 $filepath = $cacheDir .'/'.$thumbname;
2203 // Save image to cache. 2157 // Save image to cache.
2204 file_put_contents($filepath, $content); 2158 file_put_contents($filepath, $content);
2205 if (resizeImage($filepath)) 2159 if (resizeImage($filepath))
@@ -2214,7 +2168,8 @@ function genThumbnail()
2214 2168
2215 // Otherwise, return an empty image (8x8 transparent gif) 2169 // Otherwise, return an empty image (8x8 transparent gif)
2216 $blankgif = base64_decode('R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7'); 2170 $blankgif = base64_decode('R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7');
2217 file_put_contents($GLOBALS['config']['CACHEDIR'].'/'.$blankname,$blankgif); // Also put something in cache so that this URL is not requested twice. 2171 // Also put something in cache so that this URL is not requested twice.
2172 file_put_contents($cacheDir .'/'. $blankname, $blankgif);
2218 header('Content-Type: image/gif'); 2173 header('Content-Type: image/gif');
2219 echo $blankgif; 2174 echo $blankgif;
2220} 2175}
@@ -2254,6 +2209,8 @@ function resizeImage($filepath)
2254 2209
2255if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=genthumbnail')) { genThumbnail(); exit; } // Thumbnail generation/cache does not need the link database. 2210if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=genthumbnail')) { genThumbnail(); exit; } // Thumbnail generation/cache does not need the link database.
2256if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) { showDailyRSS(); exit; } 2211if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) { showDailyRSS(); exit; }
2257if (!isset($_SESSION['LINKS_PER_PAGE'])) $_SESSION['LINKS_PER_PAGE']=$GLOBALS['config']['LINKS_PER_PAGE']; 2212if (!isset($_SESSION['LINKS_PER_PAGE'])) {
2213 $_SESSION['LINKS_PER_PAGE'] = $conf->get('config.LINKS_PER_PAGE', 20);
2214}
2258renderPage(); 2215renderPage();
2259?> 2216?>
diff --git a/tests/ApplicationUtilsTest.php b/tests/ApplicationUtilsTest.php
index 6064357d..cf82b655 100644
--- a/tests/ApplicationUtilsTest.php
+++ b/tests/ApplicationUtilsTest.php
@@ -3,6 +3,7 @@
3 * ApplicationUtils' tests 3 * ApplicationUtils' tests
4 */ 4 */
5 5
6require_once 'application/config/ConfigManager.php';
6require_once 'application/ApplicationUtils.php'; 7require_once 'application/ApplicationUtils.php';
7 8
8/** 9/**
@@ -59,7 +60,7 @@ class ApplicationUtilsTest extends PHPUnit_Framework_TestCase
59 $testTimeout 60 $testTimeout
60 ) 61 )
61 ); 62 );
62 $this->assertRegexp( 63 $this->assertRegExp(
63 self::$versionPattern, 64 self::$versionPattern,
64 ApplicationUtils::getLatestGitVersionCode( 65 ApplicationUtils::getLatestGitVersionCode(
65 'https://raw.githubusercontent.com/shaarli/Shaarli/' 66 'https://raw.githubusercontent.com/shaarli/Shaarli/'
@@ -275,21 +276,21 @@ class ApplicationUtilsTest extends PHPUnit_Framework_TestCase
275 */ 276 */
276 public function testCheckCurrentResourcePermissions() 277 public function testCheckCurrentResourcePermissions()
277 { 278 {
278 $config = array( 279 $conf = ConfigManager::getInstance();
279 'CACHEDIR' => 'cache', 280 $conf->set('config.CACHEDIR', 'cache');
280 'CONFIG_FILE' => 'data/config.php', 281 $conf->set('config.CONFIG_FILE', 'data/config.php');
281 'DATADIR' => 'data', 282 $conf->set('config.DATADIR', 'data');
282 'DATASTORE' => 'data/datastore.php', 283 $conf->set('config.DATASTORE', 'data/datastore.php');
283 'IPBANS_FILENAME' => 'data/ipbans.php', 284 $conf->set('config.IPBANS_FILENAME', 'data/ipbans.php');
284 'LOG_FILE' => 'data/log.txt', 285 $conf->set('config.LOG_FILE', 'data/log.txt');
285 'PAGECACHE' => 'pagecache', 286 $conf->set('config.PAGECACHE', 'pagecache');
286 'RAINTPL_TMP' => 'tmp', 287 $conf->set('config.RAINTPL_TMP', 'tmp');
287 'RAINTPL_TPL' => 'tpl', 288 $conf->set('config.RAINTPL_TPL', 'tpl');
288 'UPDATECHECK_FILENAME' => 'data/lastupdatecheck.txt' 289 $conf->set('config.UPDATECHECK_FILENAME', 'data/lastupdatecheck.txt');
289 ); 290
290 $this->assertEquals( 291 $this->assertEquals(
291 array(), 292 array(),
292 ApplicationUtils::checkResourcePermissions($config) 293 ApplicationUtils::checkResourcePermissions()
293 ); 294 );
294 } 295 }
295 296
@@ -298,18 +299,17 @@ class ApplicationUtilsTest extends PHPUnit_Framework_TestCase
298 */ 299 */
299 public function testCheckCurrentResourcePermissionsErrors() 300 public function testCheckCurrentResourcePermissionsErrors()
300 { 301 {
301 $config = array( 302 $conf = ConfigManager::getInstance();
302 'CACHEDIR' => 'null/cache', 303 $conf->set('config.CACHEDIR', 'null/cache');
303 'CONFIG_FILE' => 'null/data/config.php', 304 $conf->set('config.CONFIG_FILE', 'null/data/config.php');
304 'DATADIR' => 'null/data', 305 $conf->set('config.DATADIR', 'null/data');
305 'DATASTORE' => 'null/data/store.php', 306 $conf->set('config.DATASTORE', 'null/data/store.php');
306 'IPBANS_FILENAME' => 'null/data/ipbans.php', 307 $conf->set('config.IPBANS_FILENAME', 'null/data/ipbans.php');
307 'LOG_FILE' => 'null/data/log.txt', 308 $conf->set('config.LOG_FILE', 'null/data/log.txt');
308 'PAGECACHE' => 'null/pagecache', 309 $conf->set('config.PAGECACHE', 'null/pagecache');
309 'RAINTPL_TMP' => 'null/tmp', 310 $conf->set('config.RAINTPL_TMP', 'null/tmp');
310 'RAINTPL_TPL' => 'null/tpl', 311 $conf->set('config.RAINTPL_TPL', 'null/tpl');
311 'UPDATECHECK_FILENAME' => 'null/data/lastupdatecheck.txt' 312 $conf->set('config.UPDATECHECK_FILENAME', 'null/data/lastupdatecheck.txt');
312 );
313 $this->assertEquals( 313 $this->assertEquals(
314 array( 314 array(
315 '"null/tpl" directory is not readable', 315 '"null/tpl" directory is not readable',
@@ -322,7 +322,7 @@ class ApplicationUtilsTest extends PHPUnit_Framework_TestCase
322 '"null/tmp" directory is not readable', 322 '"null/tmp" directory is not readable',
323 '"null/tmp" directory is not writable' 323 '"null/tmp" directory is not writable'
324 ), 324 ),
325 ApplicationUtils::checkResourcePermissions($config) 325 ApplicationUtils::checkResourcePermissions()
326 ); 326 );
327 } 327 }
328} 328}
diff --git a/tests/ConfigTest.php b/tests/ConfigTest.php
deleted file mode 100644
index 7200aae6..00000000
--- a/tests/ConfigTest.php
+++ /dev/null
@@ -1,244 +0,0 @@
1<?php
2/**
3 * Config' tests
4 */
5
6require_once 'application/Config.php';
7
8/**
9 * Unitary tests for Shaarli config related functions
10 */
11class ConfigTest extends PHPUnit_Framework_TestCase
12{
13 // Configuration input set.
14 private static $configFields;
15
16 /**
17 * Executed before each test.
18 */
19 public function setUp()
20 {
21 self::$configFields = array(
22 'login' => 'login',
23 'hash' => 'hash',
24 'salt' => 'salt',
25 'timezone' => 'Europe/Paris',
26 'title' => 'title',
27 'titleLink' => 'titleLink',
28 'redirector' => '',
29 'disablesessionprotection' => false,
30 'privateLinkByDefault' => false,
31 'config' => array(
32 'CONFIG_FILE' => 'tests/config.php',
33 'DATADIR' => 'tests',
34 'config1' => 'config1data',
35 'config2' => 'config2data',
36 )
37 );
38 }
39
40 /**
41 * Executed after each test.
42 *
43 * @return void
44 */
45 public function tearDown()
46 {
47 if (is_file(self::$configFields['config']['CONFIG_FILE'])) {
48 unlink(self::$configFields['config']['CONFIG_FILE']);
49 }
50 }
51
52 /**
53 * Test writeConfig function, valid use case, while being logged in.
54 */
55 public function testWriteConfig()
56 {
57 writeConfig(self::$configFields, true);
58
59 include self::$configFields['config']['CONFIG_FILE'];
60 $this->assertEquals(self::$configFields['login'], $GLOBALS['login']);
61 $this->assertEquals(self::$configFields['hash'], $GLOBALS['hash']);
62 $this->assertEquals(self::$configFields['salt'], $GLOBALS['salt']);
63 $this->assertEquals(self::$configFields['timezone'], $GLOBALS['timezone']);
64 $this->assertEquals(self::$configFields['title'], $GLOBALS['title']);
65 $this->assertEquals(self::$configFields['titleLink'], $GLOBALS['titleLink']);
66 $this->assertEquals(self::$configFields['redirector'], $GLOBALS['redirector']);
67 $this->assertEquals(self::$configFields['disablesessionprotection'], $GLOBALS['disablesessionprotection']);
68 $this->assertEquals(self::$configFields['privateLinkByDefault'], $GLOBALS['privateLinkByDefault']);
69 $this->assertEquals(self::$configFields['config']['config1'], $GLOBALS['config']['config1']);
70 $this->assertEquals(self::$configFields['config']['config2'], $GLOBALS['config']['config2']);
71 }
72
73 /**
74 * Test writeConfig option while logged in:
75 * 1. init fields.
76 * 2. update fields, add new sub config, add new root config.
77 * 3. rewrite config.
78 * 4. check result.
79 */
80 public function testWriteConfigFieldUpdate()
81 {
82 writeConfig(self::$configFields, true);
83 self::$configFields['title'] = 'ok';
84 self::$configFields['config']['config1'] = 'ok';
85 self::$configFields['config']['config_new'] = 'ok';
86 self::$configFields['new'] = 'should not be saved';
87 writeConfig(self::$configFields, true);
88
89 include self::$configFields['config']['CONFIG_FILE'];
90 $this->assertEquals('ok', $GLOBALS['title']);
91 $this->assertEquals('ok', $GLOBALS['config']['config1']);
92 $this->assertEquals('ok', $GLOBALS['config']['config_new']);
93 $this->assertFalse(isset($GLOBALS['new']));
94 }
95
96 /**
97 * Test writeConfig function with an empty array.
98 *
99 * @expectedException MissingFieldConfigException
100 */
101 public function testWriteConfigEmpty()
102 {
103 writeConfig(array(), true);
104 }
105
106 /**
107 * Test writeConfig function with a missing mandatory field.
108 *
109 * @expectedException MissingFieldConfigException
110 */
111 public function testWriteConfigMissingField()
112 {
113 unset(self::$configFields['login']);
114 writeConfig(self::$configFields, true);
115 }
116
117 /**
118 * Test writeConfig function while being logged out, and there is no config file existing.
119 */
120 public function testWriteConfigLoggedOutNoFile()
121 {
122 writeConfig(self::$configFields, false);
123 }
124
125 /**
126 * Test writeConfig function while being logged out, and a config file already exists.
127 *
128 * @expectedException UnauthorizedConfigException
129 */
130 public function testWriteConfigLoggedOutWithFile()
131 {
132 file_put_contents(self::$configFields['config']['CONFIG_FILE'], '');
133 writeConfig(self::$configFields, false);
134 }
135
136 /**
137 * Test save_plugin_config with valid data.
138 *
139 * @throws PluginConfigOrderException
140 */
141 public function testSavePluginConfigValid()
142 {
143 $data = array(
144 'order_plugin1' => 2, // no plugin related
145 'plugin2' => 0, // new - at the end
146 'plugin3' => 0, // 2nd
147 'order_plugin3' => 8,
148 'plugin4' => 0, // 1st
149 'order_plugin4' => 5,
150 );
151
152 $expected = array(
153 'plugin3',
154 'plugin4',
155 'plugin2',
156 );
157
158 $out = save_plugin_config($data);
159 $this->assertEquals($expected, $out);
160 }
161
162 /**
163 * Test save_plugin_config with invalid data.
164 *
165 * @expectedException PluginConfigOrderException
166 */
167 public function testSavePluginConfigInvalid()
168 {
169 $data = array(
170 'plugin2' => 0,
171 'plugin3' => 0,
172 'order_plugin3' => 0,
173 'plugin4' => 0,
174 'order_plugin4' => 0,
175 );
176
177 save_plugin_config($data);
178 }
179
180 /**
181 * Test save_plugin_config without data.
182 */
183 public function testSavePluginConfigEmpty()
184 {
185 $this->assertEquals(array(), save_plugin_config(array()));
186 }
187
188 /**
189 * Test validate_plugin_order with valid data.
190 */
191 public function testValidatePluginOrderValid()
192 {
193 $data = array(
194 'order_plugin1' => 2,
195 'plugin2' => 0,
196 'plugin3' => 0,
197 'order_plugin3' => 1,
198 'plugin4' => 0,
199 'order_plugin4' => 5,
200 );
201
202 $this->assertTrue(validate_plugin_order($data));
203 }
204
205 /**
206 * Test validate_plugin_order with invalid data.
207 */
208 public function testValidatePluginOrderInvalid()
209 {
210 $data = array(
211 'order_plugin1' => 2,
212 'order_plugin3' => 1,
213 'order_plugin4' => 1,
214 );
215
216 $this->assertFalse(validate_plugin_order($data));
217 }
218
219 /**
220 * Test load_plugin_parameter_values.
221 */
222 public function testLoadPluginParameterValues()
223 {
224 $plugins = array(
225 'plugin_name' => array(
226 'parameters' => array(
227 'param1' => true,
228 'param2' => false,
229 'param3' => '',
230 )
231 )
232 );
233
234 $parameters = array(
235 'param1' => 'value1',
236 'param2' => 'value2',
237 );
238
239 $result = load_plugin_parameter_values($plugins, $parameters);
240 $this->assertEquals('value1', $result['plugin_name']['parameters']['param1']);
241 $this->assertEquals('value2', $result['plugin_name']['parameters']['param2']);
242 $this->assertEquals('', $result['plugin_name']['parameters']['param3']);
243 }
244}
diff --git a/tests/FeedBuilderTest.php b/tests/FeedBuilderTest.php
index 069b1581..a4d6960c 100644
--- a/tests/FeedBuilderTest.php
+++ b/tests/FeedBuilderTest.php
@@ -76,7 +76,7 @@ class FeedBuilderTest extends PHPUnit_Framework_TestCase
76 // Test headers (RSS) 76 // Test headers (RSS)
77 $this->assertEquals(self::$RSS_LANGUAGE, $data['language']); 77 $this->assertEquals(self::$RSS_LANGUAGE, $data['language']);
78 $this->assertEmpty($data['pubsubhub_url']); 78 $this->assertEmpty($data['pubsubhub_url']);
79 $this->assertEquals('Tue, 10 Mar 2015 11:46:51 +0100', $data['last_update']); 79 $this->assertRegExp('/Tue, 10 Mar 2015 11:46:51 \+\d{4}/', $data['last_update']);
80 $this->assertEquals(true, $data['show_dates']); 80 $this->assertEquals(true, $data['show_dates']);
81 $this->assertEquals('http://host.tld/index.php?do=feed', $data['self_link']); 81 $this->assertEquals('http://host.tld/index.php?do=feed', $data['self_link']);
82 $this->assertEquals('http://host.tld/', $data['index_url']); 82 $this->assertEquals('http://host.tld/', $data['index_url']);
@@ -88,7 +88,7 @@ class FeedBuilderTest extends PHPUnit_Framework_TestCase
88 $this->assertEquals('20150310_114651', $link['linkdate']); 88 $this->assertEquals('20150310_114651', $link['linkdate']);
89 $this->assertEquals('http://host.tld/?WDWyig', $link['guid']); 89 $this->assertEquals('http://host.tld/?WDWyig', $link['guid']);
90 $this->assertEquals('http://host.tld/?WDWyig', $link['url']); 90 $this->assertEquals('http://host.tld/?WDWyig', $link['url']);
91 $this->assertEquals('Tue, 10 Mar 2015 11:46:51 +0100', $link['iso_date']); 91 $this->assertRegExp('/Tue, 10 Mar 2015 11:46:51 \+\d{4}/', $link['iso_date']);
92 $this->assertContains('Stallman has a beard', $link['description']); 92 $this->assertContains('Stallman has a beard', $link['description']);
93 $this->assertContains('Permalink', $link['description']); 93 $this->assertContains('Permalink', $link['description']);
94 $this->assertContains('http://host.tld/?WDWyig', $link['description']); 94 $this->assertContains('http://host.tld/?WDWyig', $link['description']);
@@ -113,7 +113,7 @@ class FeedBuilderTest extends PHPUnit_Framework_TestCase
113 $data = $feedBuilder->buildData(); 113 $data = $feedBuilder->buildData();
114 $this->assertEquals(ReferenceLinkDB::$NB_LINKS_TOTAL, count($data['links'])); 114 $this->assertEquals(ReferenceLinkDB::$NB_LINKS_TOTAL, count($data['links']));
115 $link = array_shift($data['links']); 115 $link = array_shift($data['links']);
116 $this->assertEquals('2015-03-10T11:46:51+01:00', $link['iso_date']); 116 $this->assertRegExp('/2015-03-10T11:46:51\+\d{2}:+\d{2}/', $link['iso_date']);
117 } 117 }
118 118
119 /** 119 /**
diff --git a/tests/LinkDBTest.php b/tests/LinkDBTest.php
index b055fe91..956be3b4 100644
--- a/tests/LinkDBTest.php
+++ b/tests/LinkDBTest.php
@@ -101,7 +101,7 @@ class LinkDBTest extends PHPUnit_Framework_TestCase
101 * Attempt to instantiate a LinkDB whereas the datastore is not writable 101 * Attempt to instantiate a LinkDB whereas the datastore is not writable
102 * 102 *
103 * @expectedException IOException 103 * @expectedException IOException
104 * @expectedExceptionMessageRegExp /Error accessing null/ 104 * @expectedExceptionMessageRegExp /Error accessing\nnull/
105 */ 105 */
106 public function testConstructDatastoreNotWriteable() 106 public function testConstructDatastoreNotWriteable()
107 { 107 {
diff --git a/tests/Updater/DummyUpdater.php b/tests/Updater/DummyUpdater.php
index e9ef2aaa..6724b203 100644
--- a/tests/Updater/DummyUpdater.php
+++ b/tests/Updater/DummyUpdater.php
@@ -12,13 +12,12 @@ class DummyUpdater extends Updater
12 * Object constructor. 12 * Object constructor.
13 * 13 *
14 * @param array $doneUpdates Updates which are already done. 14 * @param array $doneUpdates Updates which are already done.
15 * @param array $config Shaarli's configuration array.
16 * @param LinkDB $linkDB LinkDB instance. 15 * @param LinkDB $linkDB LinkDB instance.
17 * @param boolean $isLoggedIn True if the user is logged in. 16 * @param boolean $isLoggedIn True if the user is logged in.
18 */ 17 */
19 public function __construct($doneUpdates, $config, $linkDB, $isLoggedIn) 18 public function __construct($doneUpdates, $linkDB, $isLoggedIn)
20 { 19 {
21 parent::__construct($doneUpdates, $config, $linkDB, $isLoggedIn); 20 parent::__construct($doneUpdates, $linkDB, $isLoggedIn);
22 21
23 // Retrieve all update methods. 22 // Retrieve all update methods.
24 // For unit test, only retrieve final methods, 23 // For unit test, only retrieve final methods,
diff --git a/tests/Updater/UpdaterTest.php b/tests/Updater/UpdaterTest.php
index a29d9067..8bfb4ba3 100644
--- a/tests/Updater/UpdaterTest.php
+++ b/tests/Updater/UpdaterTest.php
@@ -1,5 +1,6 @@
1<?php 1<?php
2 2
3require_once 'application/config/ConfigManager.php';
3require_once 'tests/Updater/DummyUpdater.php'; 4require_once 'tests/Updater/DummyUpdater.php';
4 5
5/** 6/**
@@ -19,6 +20,16 @@ class UpdaterTest extends PHPUnit_Framework_TestCase
19 protected static $testDatastore = 'sandbox/datastore.php'; 20 protected static $testDatastore = 'sandbox/datastore.php';
20 21
21 /** 22 /**
23 * @var string Config file path.
24 */
25 protected static $configFile = 'tests/Updater/config.php';
26
27 /**
28 * @var ConfigManager
29 */
30 protected $conf;
31
32 /**
22 * Executed before each test. 33 * Executed before each test.
23 */ 34 */
24 public function setUp() 35 public function setUp()
@@ -34,13 +45,19 @@ class UpdaterTest extends PHPUnit_Framework_TestCase
34 'disablesessionprotection' => false, 45 'disablesessionprotection' => false,
35 'privateLinkByDefault' => false, 46 'privateLinkByDefault' => false,
36 'config' => array( 47 'config' => array(
37 'CONFIG_FILE' => 'tests/Updater/config.php',
38 'DATADIR' => 'tests/Updater', 48 'DATADIR' => 'tests/Updater',
39 'PAGECACHE' => 'sandbox/pagecache', 49 'PAGECACHE' => 'sandbox/pagecache',
40 'config1' => 'config1data', 50 'config1' => 'config1data',
41 'config2' => 'config2data', 51 'config2' => 'config2data',
42 ) 52 )
43 ); 53 );
54
55 ConfigManager::$CONFIG_FILE = 'tests/Updater/config';
56 $this->conf = ConfigManager::getInstance();
57 foreach (self::$configFields as $key => $value) {
58 $this->conf->set($key, $value);
59 }
60 $this->conf->write(true);
44 } 61 }
45 62
46 /** 63 /**
@@ -50,16 +67,16 @@ class UpdaterTest extends PHPUnit_Framework_TestCase
50 */ 67 */
51 public function tearDown() 68 public function tearDown()
52 { 69 {
53 if (is_file(self::$configFields['config']['CONFIG_FILE'])) { 70 if (is_file(self::$configFile)) {
54 unlink(self::$configFields['config']['CONFIG_FILE']); 71 unlink(self::$configFile);
55 } 72 }
56 73
57 if (is_file(self::$configFields['config']['DATADIR'] . '/options.php')) { 74 if (is_file(self::$configFields['config']['DATADIR'] . '/options.php')) {
58 unlink(self::$configFields['config']['DATADIR'] . '/options.php'); 75 unlink(self::$configFields['config']['DATADIR'] . '/options.php');
59 } 76 }
60 77
61 if (is_file(self::$configFields['config']['DATADIR'] . '/updates.json')) { 78 if (is_file(self::$configFields['config']['DATADIR'] . '/updates.txt')) {
62 unlink(self::$configFields['config']['DATADIR'] . '/updates.json'); 79 unlink(self::$configFields['config']['DATADIR'] . '/updates.txt');
63 } 80 }
64 } 81 }
65 82
@@ -69,7 +86,7 @@ class UpdaterTest extends PHPUnit_Framework_TestCase
69 public function testReadEmptyUpdatesFile() 86 public function testReadEmptyUpdatesFile()
70 { 87 {
71 $this->assertEquals(array(), read_updates_file('')); 88 $this->assertEquals(array(), read_updates_file(''));
72 $updatesFile = self::$configFields['config']['DATADIR'] . '/updates.json'; 89 $updatesFile = self::$configFields['config']['DATADIR'] . '/updates.txt';
73 touch($updatesFile); 90 touch($updatesFile);
74 $this->assertEquals(array(), read_updates_file($updatesFile)); 91 $this->assertEquals(array(), read_updates_file($updatesFile));
75 } 92 }
@@ -79,7 +96,7 @@ class UpdaterTest extends PHPUnit_Framework_TestCase
79 */ 96 */
80 public function testReadWriteUpdatesFile() 97 public function testReadWriteUpdatesFile()
81 { 98 {
82 $updatesFile = self::$configFields['config']['DATADIR'] . '/updates.json'; 99 $updatesFile = self::$configFields['config']['DATADIR'] . '/updates.txt';
83 $updatesMethods = array('m1', 'm2', 'm3'); 100 $updatesMethods = array('m1', 'm2', 'm3');
84 101
85 write_updates_file($updatesFile, $updatesMethods); 102 write_updates_file($updatesFile, $updatesMethods);
@@ -112,7 +129,7 @@ class UpdaterTest extends PHPUnit_Framework_TestCase
112 */ 129 */
113 public function testWriteUpdatesFileNotWritable() 130 public function testWriteUpdatesFileNotWritable()
114 { 131 {
115 $updatesFile = self::$configFields['config']['DATADIR'] . '/updates.json'; 132 $updatesFile = self::$configFields['config']['DATADIR'] . '/updates.txt';
116 touch($updatesFile); 133 touch($updatesFile);
117 chmod($updatesFile, 0444); 134 chmod($updatesFile, 0444);
118 @write_updates_file($updatesFile, array('test')); 135 @write_updates_file($updatesFile, array('test'));
@@ -131,10 +148,10 @@ class UpdaterTest extends PHPUnit_Framework_TestCase
131 'updateMethodDummy3', 148 'updateMethodDummy3',
132 'updateMethodException', 149 'updateMethodException',
133 ); 150 );
134 $updater = new DummyUpdater($updates, array(), array(), true); 151 $updater = new DummyUpdater($updates, array(), true);
135 $this->assertEquals(array(), $updater->update()); 152 $this->assertEquals(array(), $updater->update());
136 153
137 $updater = new DummyUpdater(array(), array(), array(), false); 154 $updater = new DummyUpdater(array(), array(), false);
138 $this->assertEquals(array(), $updater->update()); 155 $this->assertEquals(array(), $updater->update());
139 } 156 }
140 157
@@ -149,7 +166,7 @@ class UpdaterTest extends PHPUnit_Framework_TestCase
149 'updateMethodDummy2', 166 'updateMethodDummy2',
150 'updateMethodDummy3', 167 'updateMethodDummy3',
151 ); 168 );
152 $updater = new DummyUpdater($updates, array(), array(), true); 169 $updater = new DummyUpdater($updates, array(), true);
153 $this->assertEquals($expectedUpdates, $updater->update()); 170 $this->assertEquals($expectedUpdates, $updater->update());
154 } 171 }
155 172
@@ -165,7 +182,7 @@ class UpdaterTest extends PHPUnit_Framework_TestCase
165 ); 182 );
166 $expectedUpdate = array('updateMethodDummy2'); 183 $expectedUpdate = array('updateMethodDummy2');
167 184
168 $updater = new DummyUpdater($updates, array(), array(), true); 185 $updater = new DummyUpdater($updates, array(), true);
169 $this->assertEquals($expectedUpdate, $updater->update()); 186 $this->assertEquals($expectedUpdate, $updater->update());
170 } 187 }
171 188
@@ -182,7 +199,7 @@ class UpdaterTest extends PHPUnit_Framework_TestCase
182 'updateMethodDummy3', 199 'updateMethodDummy3',
183 ); 200 );
184 201
185 $updater = new DummyUpdater($updates, array(), array(), true); 202 $updater = new DummyUpdater($updates, array(), true);
186 $updater->update(); 203 $updater->update();
187 } 204 }
188 205
@@ -195,26 +212,25 @@ class UpdaterTest extends PHPUnit_Framework_TestCase
195 */ 212 */
196 public function testUpdateMergeDeprecatedConfig() 213 public function testUpdateMergeDeprecatedConfig()
197 { 214 {
198 // init
199 writeConfig(self::$configFields, true);
200 $configCopy = self::$configFields;
201 $invert = !$configCopy['privateLinkByDefault'];
202 $configCopy['privateLinkByDefault'] = $invert;
203
204 // Use writeConfig to create a options.php 215 // Use writeConfig to create a options.php
205 $configCopy['config']['CONFIG_FILE'] = 'tests/Updater/options.php'; 216 ConfigManager::$CONFIG_FILE = 'tests/Updater/options';
206 writeConfig($configCopy, true); 217 $invert = !$this->conf->get('privateLinkByDefault');
218 $this->conf->set('privateLinkByDefault', $invert);
219 $this->conf->write(true);
220
221 $optionsFile = 'tests/Updater/options.php';
222 $this->assertTrue(is_file($optionsFile));
207 223
208 $this->assertTrue(is_file($configCopy['config']['CONFIG_FILE'])); 224 ConfigManager::$CONFIG_FILE = 'tests/Updater/config';
209 225
210 // merge configs 226 // merge configs
211 $updater = new Updater(array(), self::$configFields, array(), true); 227 $updater = new Updater(array(), array(), true);
212 $updater->updateMethodMergeDeprecatedConfigFile(); 228 $updater->updateMethodMergeDeprecatedConfigFile();
213 229
214 // make sure updated field is changed 230 // make sure updated field is changed
215 include self::$configFields['config']['CONFIG_FILE']; 231 $this->conf->reload();
216 $this->assertEquals($invert, $GLOBALS['privateLinkByDefault']); 232 $this->assertEquals($invert, $this->conf->get('privateLinkByDefault'));
217 $this->assertFalse(is_file($configCopy['config']['CONFIG_FILE'])); 233 $this->assertFalse(is_file($optionsFile));
218 } 234 }
219 235
220 /** 236 /**
@@ -222,22 +238,22 @@ class UpdaterTest extends PHPUnit_Framework_TestCase
222 */ 238 */
223 public function testMergeDeprecatedConfigNoFile() 239 public function testMergeDeprecatedConfigNoFile()
224 { 240 {
225 writeConfig(self::$configFields, true); 241 $updater = new Updater(array(), array(), true);
226
227 $updater = new Updater(array(), self::$configFields, array(), true);
228 $updater->updateMethodMergeDeprecatedConfigFile(); 242 $updater->updateMethodMergeDeprecatedConfigFile();
229 243
230 include self::$configFields['config']['CONFIG_FILE']; 244 $this->assertEquals(self::$configFields['login'], $this->conf->get('login'));
231 $this->assertEquals(self::$configFields['login'], $GLOBALS['login']);
232 } 245 }
233 246
247 /**
248 * Test renameDashTags update method.
249 */
234 public function testRenameDashTags() 250 public function testRenameDashTags()
235 { 251 {
236 $refDB = new ReferenceLinkDB(); 252 $refDB = new ReferenceLinkDB();
237 $refDB->write(self::$testDatastore); 253 $refDB->write(self::$testDatastore);
238 $linkDB = new LinkDB(self::$testDatastore, true, false); 254 $linkDB = new LinkDB(self::$testDatastore, true, false);
239 $this->assertEmpty($linkDB->filterSearch(array('searchtags' => 'exclude'))); 255 $this->assertEmpty($linkDB->filterSearch(array('searchtags' => 'exclude')));
240 $updater = new Updater(array(), self::$configFields, $linkDB, true); 256 $updater = new Updater(array(), $linkDB, true);
241 $updater->updateMethodRenameDashTags(); 257 $updater->updateMethodRenameDashTags();
242 $this->assertNotEmpty($linkDB->filterSearch(array('searchtags' => 'exclude'))); 258 $this->assertNotEmpty($linkDB->filterSearch(array('searchtags' => 'exclude')));
243 } 259 }
diff --git a/tests/config/ConfigPhpTest.php b/tests/config/ConfigPhpTest.php
index 0f849bd5..58cd8d2a 100644
--- a/tests/config/ConfigPhpTest.php
+++ b/tests/config/ConfigPhpTest.php
@@ -22,7 +22,7 @@ class ConfigPhpTest extends PHPUnit_Framework_TestCase
22 */ 22 */
23 public function testRead() 23 public function testRead()
24 { 24 {
25 $conf = $this->configIO->read('tests/config/php/configOK'); 25 $conf = $this->configIO->read('tests/utils/config/configPhp.php');
26 $this->assertEquals('root', $conf['login']); 26 $this->assertEquals('root', $conf['login']);
27 $this->assertEquals('lala', $conf['redirector']); 27 $this->assertEquals('lala', $conf['redirector']);
28 $this->assertEquals('data/datastore.php', $conf['config']['DATASTORE']); 28 $this->assertEquals('data/datastore.php', $conf['config']['DATASTORE']);
@@ -42,7 +42,7 @@ class ConfigPhpTest extends PHPUnit_Framework_TestCase
42 */ 42 */
43 public function testWriteNew() 43 public function testWriteNew()
44 { 44 {
45 $dataFile = 'tests/config/php/configWrite'; 45 $dataFile = 'tests/utils/config/configWrite.php';
46 $data = array( 46 $data = array(
47 'login' => 'root', 47 'login' => 'root',
48 'redirector' => 'lala', 48 'redirector' => 'lala',
@@ -60,8 +60,8 @@ $GLOBALS[\'redirector\'] = \'lala\';
60$GLOBALS[\'config\'][\'DATASTORE\'] = \'data/datastore.php\'; 60$GLOBALS[\'config\'][\'DATASTORE\'] = \'data/datastore.php\';
61$GLOBALS[\'plugins\'][\'WALLABAG_VERSION\'] = \'1\'; 61$GLOBALS[\'plugins\'][\'WALLABAG_VERSION\'] = \'1\';
62'; 62';
63 $this->assertEquals($expected, file_get_contents($dataFile .'.php')); 63 $this->assertEquals($expected, file_get_contents($dataFile));
64 unlink($dataFile .'.php'); 64 unlink($dataFile);
65 } 65 }
66 66
67 /** 67 /**
@@ -69,14 +69,14 @@ $GLOBALS[\'plugins\'][\'WALLABAG_VERSION\'] = \'1\';
69 */ 69 */
70 public function testOverwrite() 70 public function testOverwrite()
71 { 71 {
72 $source = 'tests/config/php/configOK.php'; 72 $source = 'tests/utils/config/configPhp.php';
73 $dest = 'tests/config/php/configOverwrite'; 73 $dest = 'tests/utils/config/configOverwrite.php';
74 copy($source, $dest . '.php'); 74 copy($source, $dest);
75 $conf = $this->configIO->read($dest); 75 $conf = $this->configIO->read($dest);
76 $conf['redirector'] = 'blabla'; 76 $conf['redirector'] = 'blabla';
77 $this->configIO->write($dest, $conf); 77 $this->configIO->write($dest, $conf);
78 $conf = $this->configIO->read($dest); 78 $conf = $this->configIO->read($dest);
79 $this->assertEquals('blabla', $conf['redirector']); 79 $this->assertEquals('blabla', $conf['redirector']);
80 unlink($dest .'.php'); 80 unlink($dest);
81 } 81 }
82} 82}
diff --git a/tests/config/php/configOK.php b/tests/config/php/configOK.php
deleted file mode 100644
index b91ad293..00000000
--- a/tests/config/php/configOK.php
+++ /dev/null
@@ -1,14 +0,0 @@
1<?php
2$GLOBALS['login'] = 'root';
3$GLOBALS['hash'] = 'hash';
4$GLOBALS['salt'] = 'salt';
5$GLOBALS['timezone'] = 'Europe/Paris';
6$GLOBALS['title'] = 'BIGBANG';
7$GLOBALS['titleLink'] = '?';
8$GLOBALS['redirector'] = 'lala';
9$GLOBALS['disablesessionprotection'] = false;
10$GLOBALS['privateLinkByDefault'] = true;
11$GLOBALS['config']['DATADIR'] = 'data';
12$GLOBALS['config']['DATASTORE'] = 'data/datastore.php';
13$GLOBALS['plugins']['WALLABAG_URL'] = 'ghf';
14$GLOBALS['plugins']['WALLABAG_VERSION'] = '1'; \ No newline at end of file
diff --git a/tests/utils/config/configPhp.php b/tests/utils/config/configPhp.php
new file mode 100644
index 00000000..0e034175
--- /dev/null
+++ b/tests/utils/config/configPhp.php
@@ -0,0 +1,14 @@
1<?php
2$GLOBALS['login'] = 'root';
3$GLOBALS['hash'] = 'hash';
4$GLOBALS['salt'] = 'salt';
5$GLOBALS['timezone'] = 'Europe/Paris';
6$GLOBALS['title'] = 'title';
7$GLOBALS['titleLink'] = 'titleLink';
8$GLOBALS['redirector'] = 'lala';
9$GLOBALS['disablesessionprotection'] = false;
10$GLOBALS['privateLinkByDefault'] = false;
11$GLOBALS['config']['DATADIR'] = 'tests/Updater';
12$GLOBALS['config']['PAGECACHE'] = 'sandbox/pagecache';
13$GLOBALS['config']['DATASTORE'] = 'data/datastore.php';
14$GLOBALS['plugins']['WALLABAG_VERSION'] = '1';
diff --git a/tests/utils/config/configUpdater.php b/tests/utils/config/configUpdater.php
new file mode 100644
index 00000000..ee4a56b5
--- /dev/null
+++ b/tests/utils/config/configUpdater.php
@@ -0,0 +1,15 @@
1<?php
2$GLOBALS['login'] = 'login';
3$GLOBALS['hash'] = 'hash';
4$GLOBALS['salt'] = 'salt';
5$GLOBALS['timezone'] = 'Europe/Paris';
6$GLOBALS['title'] = 'title';
7$GLOBALS['titleLink'] = 'titleLink';
8$GLOBALS['redirector'] = '';
9$GLOBALS['disablesessionprotection'] = false;
10$GLOBALS['privateLinkByDefault'] = false;
11$GLOBALS['config']['DATADIR'] = 'tests/Updater';
12$GLOBALS['config']['PAGECACHE'] = 'sandbox/pagecache';
13$GLOBALS['config']['config1'] = 'config1data';
14$GLOBALS['config']['config2'] = 'config2data';
15$GLOBALS['plugins']['WALLABAG_VERSION'] = '2';
diff --git a/tpl/configure.html b/tpl/configure.html
index b7f87c68..f99fa45b 100644
--- a/tpl/configure.html
+++ b/tpl/configure.html
@@ -47,7 +47,7 @@
47 <td valign="top"><b>New link:</b></td> 47 <td valign="top"><b>New link:</b></td>
48 <td> 48 <td>
49 <input type="checkbox" name="privateLinkByDefault" id="privateLinkByDefault" 49 <input type="checkbox" name="privateLinkByDefault" id="privateLinkByDefault"
50 {if="!empty($GLOBALS['privateLinkByDefault'])"}checked{/if}/> 50 {if="$private_links_default"}checked{/if}/>
51 <label for="privateLinkByDefault"> 51 <label for="privateLinkByDefault">
52 &nbsp;All new links are private by default 52 &nbsp;All new links are private by default
53 </label> 53 </label>
@@ -57,7 +57,7 @@
57 <td valign="top"><b>RSS direct links</b></td> 57 <td valign="top"><b>RSS direct links</b></td>
58 <td> 58 <td>
59 <input type="checkbox" name="enableRssPermalinks" id="enableRssPermalinks" 59 <input type="checkbox" name="enableRssPermalinks" id="enableRssPermalinks"
60 {if="!empty($GLOBALS['config']['ENABLE_RSS_PERMALINKS'])"}checked{/if}/> 60 {if="$enable_rss_permalinks"}checked{/if}/>
61 <label for="enableRssPermalinks"> 61 <label for="enableRssPermalinks">
62 &nbsp;Disable it to use permalinks in RSS feed instead of direct links to your shaared links. Currently <b> 62 &nbsp;Disable it to use permalinks in RSS feed instead of direct links to your shaared links. Currently <b>
63 {if="$GLOBALS['config']['ENABLE_RSS_PERMALINKS']"}enabled{else}disabled{/if}.</b> 63 {if="$GLOBALS['config']['ENABLE_RSS_PERMALINKS']"}enabled{else}disabled{/if}.</b>
@@ -68,7 +68,7 @@
68 <td valign="top"><b>Hide public links</b></td> 68 <td valign="top"><b>Hide public links</b></td>
69 <td> 69 <td>
70 <input type="checkbox" name="hidePublicLinks" id="hidePublicLinks" 70 <input type="checkbox" name="hidePublicLinks" id="hidePublicLinks"
71 {if="!empty($GLOBALS['config']['HIDE_PUBLIC_LINKS'])"}checked{/if}/> 71 {if="$hide_public_links"}checked{/if}/>
72 <label for="hidePublicLinks">&nbsp;Do not show any links if the user is not logged in.</label> 72 <label for="hidePublicLinks">&nbsp;Do not show any links if the user is not logged in.</label>
73 </td> 73 </td>
74 </tr> 74 </tr>
@@ -76,7 +76,7 @@
76 <td valign="top"><b>Update:</b></td> 76 <td valign="top"><b>Update:</b></td>
77 <td> 77 <td>
78 <input type="checkbox" name="updateCheck" id="updateCheck" 78 <input type="checkbox" name="updateCheck" id="updateCheck"
79 {if="!empty($GLOBALS['config']['ENABLE_UPDATECHECK'])"}checked{/if}/> 79 {if="$enable_update_check"}checked{/if}/>
80 <label for="updateCheck">&nbsp;Notify me when a new release is ready</label> 80 <label for="updateCheck">&nbsp;Notify me when a new release is ready</label>
81 </td> 81 </td>
82 </tr> 82 </tr>
diff --git a/tpl/page.header.html b/tpl/page.header.html
index 3a09ecd9..0012c689 100644
--- a/tpl/page.header.html
+++ b/tpl/page.header.html
@@ -21,14 +21,14 @@
21 <li><a href="?do=logout">Logout</a></li> 21 <li><a href="?do=logout">Logout</a></li>
22 <li><a href="?do=tools">Tools</a></li> 22 <li><a href="?do=tools">Tools</a></li>
23 <li><a href="?do=addlink">Add link</a></li> 23 <li><a href="?do=addlink">Add link</a></li>
24 {elseif="$GLOBALS['config']['OPEN_SHAARLI']"} 24 {elseif="$openshaarli"}
25 <li><a href="?do=tools">Tools</a></li> 25 <li><a href="?do=tools">Tools</a></li>
26 <li><a href="?do=addlink">Add link</a></li> 26 <li><a href="?do=addlink">Add link</a></li>
27 {else} 27 {else}
28 <li><a href="?do=login">Login</a></li> 28 <li><a href="?do=login">Login</a></li>
29 {/if} 29 {/if}
30 <li><a href="{$feedurl}?do=rss{$searchcrits}" class="nomobile">RSS Feed</a></li> 30 <li><a href="{$feedurl}?do=rss{$searchcrits}" class="nomobile">RSS Feed</a></li>
31 {if="$GLOBALS['config']['SHOW_ATOM']"} 31 {if="$showatom"}
32 <li><a href="{$feedurl}?do=atom{$searchcrits}" class="nomobile">ATOM Feed</a></li> 32 <li><a href="{$feedurl}?do=atom{$searchcrits}" class="nomobile">ATOM Feed</a></li>
33 {/if} 33 {/if}
34 <li><a href="?do=tagcloud">Tag cloud</a></li> 34 <li><a href="?do=tagcloud">Tag cloud</a></li>