aboutsummaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--application/ApplicationUtils.php7
-rw-r--r--application/PageBuilder.php48
-rw-r--r--application/Updater.php57
-rw-r--r--application/config/ConfigManager.php84
-rw-r--r--index.php317
-rw-r--r--tests/ApplicationUtilsTest.php8
-rw-r--r--tests/Updater/DummyUpdater.php11
-rw-r--r--tests/Updater/UpdaterTest.php57
-rw-r--r--tests/config/ConfigManagerTest.php28
9 files changed, 342 insertions, 275 deletions
diff --git a/application/ApplicationUtils.php b/application/ApplicationUtils.php
index 37deb4b3..c5a157b9 100644
--- a/application/ApplicationUtils.php
+++ b/application/ApplicationUtils.php
@@ -132,12 +132,13 @@ 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 ConfigManager $conf Configuration Manager instance.
136 *
135 * @return array A list of the detected configuration issues 137 * @return array A list of the detected configuration issues
136 */ 138 */
137 public static function checkResourcePermissions() 139 public static function checkResourcePermissions($conf)
138 { 140 {
139 $errors = array(); 141 $errors = array();
140 $conf = ConfigManager::getInstance();
141 142
142 // Check script and template directories are readable 143 // Check script and template directories are readable
143 foreach (array( 144 foreach (array(
@@ -168,7 +169,7 @@ class ApplicationUtils
168 169
169 // Check configuration files are readable and writeable 170 // Check configuration files are readable and writeable
170 foreach (array( 171 foreach (array(
171 $conf->getConfigFile(), 172 $conf->getConfigFileExt(),
172 $conf->get('path.datastore'), 173 $conf->get('path.datastore'),
173 $conf->get('path.ban_file'), 174 $conf->get('path.ban_file'),
174 $conf->get('path.log'), 175 $conf->get('path.log'),
diff --git a/application/PageBuilder.php b/application/PageBuilder.php
index 04454865..843cc0dc 100644
--- a/application/PageBuilder.php
+++ b/application/PageBuilder.php
@@ -15,12 +15,20 @@ class PageBuilder
15 private $tpl; 15 private $tpl;
16 16
17 /** 17 /**
18 * @var ConfigManager $conf Configuration Manager instance.
19 */
20 protected $conf;
21
22 /**
18 * PageBuilder constructor. 23 * PageBuilder constructor.
19 * $tpl is initialized at false for lazy loading. 24 * $tpl is initialized at false for lazy loading.
25 *
26 * @param ConfigManager $conf Configuration Manager instance (reference).
20 */ 27 */
21 function __construct() 28 function __construct(&$conf)
22 { 29 {
23 $this->tpl = false; 30 $this->tpl = false;
31 $this->conf = $conf;
24 } 32 }
25 33
26 /** 34 /**
@@ -29,22 +37,21 @@ class PageBuilder
29 private function initialize() 37 private function initialize()
30 { 38 {
31 $this->tpl = new RainTPL(); 39 $this->tpl = new RainTPL();
32 $conf = ConfigManager::getInstance();
33 40
34 try { 41 try {
35 $version = ApplicationUtils::checkUpdate( 42 $version = ApplicationUtils::checkUpdate(
36 shaarli_version, 43 shaarli_version,
37 $conf->get('path.update_check'), 44 $this->conf->get('path.update_check'),
38 $conf->get('general.check_updates_interval'), 45 $this->conf->get('general.check_updates_interval'),
39 $conf->get('general.check_updates'), 46 $this->conf->get('general.check_updates'),
40 isLoggedIn(), 47 isLoggedIn(),
41 $conf->get('general.check_updates_branch') 48 $this->conf->get('general.check_updates_branch')
42 ); 49 );
43 $this->tpl->assign('newVersion', escape($version)); 50 $this->tpl->assign('newVersion', escape($version));
44 $this->tpl->assign('versionError', ''); 51 $this->tpl->assign('versionError', '');
45 52
46 } catch (Exception $exc) { 53 } catch (Exception $exc) {
47 logm($conf->get('path.log'), $_SERVER['REMOTE_ADDR'], $exc->getMessage()); 54 logm($this->conf->get('path.log'), $_SERVER['REMOTE_ADDR'], $exc->getMessage());
48 $this->tpl->assign('newVersion', ''); 55 $this->tpl->assign('newVersion', '');
49 $this->tpl->assign('versionError', escape($exc->getMessage())); 56 $this->tpl->assign('versionError', escape($exc->getMessage()));
50 } 57 }
@@ -63,19 +70,19 @@ class PageBuilder
63 $this->tpl->assign('scripturl', index_url($_SERVER)); 70 $this->tpl->assign('scripturl', index_url($_SERVER));
64 $this->tpl->assign('pagetitle', 'Shaarli'); 71 $this->tpl->assign('pagetitle', 'Shaarli');
65 $this->tpl->assign('privateonly', !empty($_SESSION['privateonly'])); // Show only private links? 72 $this->tpl->assign('privateonly', !empty($_SESSION['privateonly'])); // Show only private links?
66 if ($conf->exists('general.title')) { 73 if ($this->conf->exists('general.title')) {
67 $this->tpl->assign('pagetitle', $conf->get('general.title')); 74 $this->tpl->assign('pagetitle', $this->conf->get('general.title'));
68 } 75 }
69 if ($conf->exists('general.header_link')) { 76 if ($this->conf->exists('general.header_link')) {
70 $this->tpl->assign('titleLink', $conf->get('general.header_link')); 77 $this->tpl->assign('titleLink', $this->conf->get('general.header_link'));
71 } 78 }
72 if ($conf->exists('pagetitle')) { 79 if ($this->conf->exists('pagetitle')) {
73 $this->tpl->assign('pagetitle', $conf->get('pagetitle')); 80 $this->tpl->assign('pagetitle', $this->conf->get('pagetitle'));
74 } 81 }
75 $this->tpl->assign('shaarlititle', $conf->get('title', 'Shaarli')); 82 $this->tpl->assign('shaarlititle', $this->conf->get('title', 'Shaarli'));
76 $this->tpl->assign('openshaarli', $conf->get('extras.open_shaarli', false)); 83 $this->tpl->assign('openshaarli', $this->conf->get('extras.open_shaarli', false));
77 $this->tpl->assign('showatom', $conf->get('extras.show_atom', false)); 84 $this->tpl->assign('showatom', $this->conf->get('extras.show_atom', false));
78 $this->tpl->assign('hide_timestamps', $conf->get('extras.hide_timestamps', false)); 85 $this->tpl->assign('hide_timestamps', $this->conf->get('extras.hide_timestamps', false));
79 if (!empty($GLOBALS['plugin_errors'])) { 86 if (!empty($GLOBALS['plugin_errors'])) {
80 $this->tpl->assign('plugin_errors', $GLOBALS['plugin_errors']); 87 $this->tpl->assign('plugin_errors', $GLOBALS['plugin_errors']);
81 } 88 }
@@ -89,7 +96,6 @@ class PageBuilder
89 */ 96 */
90 public function assign($placeholder, $value) 97 public function assign($placeholder, $value)
91 { 98 {
92 // Lazy initialization
93 if ($this->tpl === false) { 99 if ($this->tpl === false) {
94 $this->initialize(); 100 $this->initialize();
95 } 101 }
@@ -105,7 +111,6 @@ class PageBuilder
105 */ 111 */
106 public function assignAll($data) 112 public function assignAll($data)
107 { 113 {
108 // Lazy initialization
109 if ($this->tpl === false) { 114 if ($this->tpl === false) {
110 $this->initialize(); 115 $this->initialize();
111 } 116 }
@@ -117,6 +122,7 @@ class PageBuilder
117 foreach ($data as $key => $value) { 122 foreach ($data as $key => $value) {
118 $this->assign($key, $value); 123 $this->assign($key, $value);
119 } 124 }
125 return true;
120 } 126 }
121 127
122 /** 128 /**
@@ -127,10 +133,10 @@ class PageBuilder
127 */ 133 */
128 public function renderPage($page) 134 public function renderPage($page)
129 { 135 {
130 // Lazy initialization 136 if ($this->tpl === false) {
131 if ($this->tpl===false) {
132 $this->initialize(); 137 $this->initialize();
133 } 138 }
139
134 $this->tpl->draw($page); 140 $this->tpl->draw($page);
135 } 141 }
136 142
diff --git a/application/Updater.php b/application/Updater.php
index db2144fe..b8940e41 100644
--- a/application/Updater.php
+++ b/application/Updater.php
@@ -18,6 +18,11 @@ class Updater
18 protected $linkDB; 18 protected $linkDB;
19 19
20 /** 20 /**
21 * @var ConfigManager $conf Configuration Manager instance.
22 */
23 protected $conf;
24
25 /**
21 * @var bool True if the user is logged in, false otherwise. 26 * @var bool True if the user is logged in, false otherwise.
22 */ 27 */
23 protected $isLoggedIn; 28 protected $isLoggedIn;
@@ -30,14 +35,16 @@ class Updater
30 /** 35 /**
31 * Object constructor. 36 * Object constructor.
32 * 37 *
33 * @param array $doneUpdates Updates which are already done. 38 * @param array $doneUpdates Updates which are already done.
34 * @param LinkDB $linkDB LinkDB instance. 39 * @param LinkDB $linkDB LinkDB instance.
35 * @param boolean $isLoggedIn True if the user is logged in. 40 * @oaram ConfigManager $conf Configuration Manager instance.
41 * @param boolean $isLoggedIn True if the user is logged in.
36 */ 42 */
37 public function __construct($doneUpdates, $linkDB, $isLoggedIn) 43 public function __construct($doneUpdates, $linkDB, $conf, $isLoggedIn)
38 { 44 {
39 $this->doneUpdates = $doneUpdates; 45 $this->doneUpdates = $doneUpdates;
40 $this->linkDB = $linkDB; 46 $this->linkDB = $linkDB;
47 $this->conf = $conf;
41 $this->isLoggedIn = $isLoggedIn; 48 $this->isLoggedIn = $isLoggedIn;
42 49
43 // Retrieve all update methods. 50 // Retrieve all update methods.
@@ -107,21 +114,19 @@ class Updater
107 */ 114 */
108 public function updateMethodMergeDeprecatedConfigFile() 115 public function updateMethodMergeDeprecatedConfigFile()
109 { 116 {
110 $conf = ConfigManager::getInstance(); 117 if (is_file($this->conf->get('path.data_dir') . '/options.php')) {
111 118 include $this->conf->get('path.data_dir') . '/options.php';
112 if (is_file($conf->get('path.data_dir') . '/options.php')) {
113 include $conf->get('path.data_dir') . '/options.php';
114 119
115 // Load GLOBALS into config 120 // Load GLOBALS into config
116 $allowedKeys = array_merge(ConfigPhp::$ROOT_KEYS); 121 $allowedKeys = array_merge(ConfigPhp::$ROOT_KEYS);
117 $allowedKeys[] = 'config'; 122 $allowedKeys[] = 'config';
118 foreach ($GLOBALS as $key => $value) { 123 foreach ($GLOBALS as $key => $value) {
119 if (in_array($key, $allowedKeys)) { 124 if (in_array($key, $allowedKeys)) {
120 $conf->set($key, $value); 125 $this->conf->set($key, $value);
121 } 126 }
122 } 127 }
123 $conf->write($this->isLoggedIn); 128 $this->conf->write($this->isLoggedIn);
124 unlink($conf->get('path.data_dir').'/options.php'); 129 unlink($this->conf->get('path.data_dir').'/options.php');
125 } 130 }
126 131
127 return true; 132 return true;
@@ -132,14 +137,13 @@ class Updater
132 */ 137 */
133 public function updateMethodRenameDashTags() 138 public function updateMethodRenameDashTags()
134 { 139 {
135 $conf = ConfigManager::getInstance();
136 $linklist = $this->linkDB->filterSearch(); 140 $linklist = $this->linkDB->filterSearch();
137 foreach ($linklist as $link) { 141 foreach ($linklist as $link) {
138 $link['tags'] = preg_replace('/(^| )\-/', '$1', $link['tags']); 142 $link['tags'] = preg_replace('/(^| )\-/', '$1', $link['tags']);
139 $link['tags'] = implode(' ', array_unique(LinkFilter::tagsStrToArray($link['tags'], true))); 143 $link['tags'] = implode(' ', array_unique(LinkFilter::tagsStrToArray($link['tags'], true)));
140 $this->linkDB[$link['linkdate']] = $link; 144 $this->linkDB[$link['linkdate']] = $link;
141 } 145 }
142 $this->linkDB->savedb($conf->get('path.page_cache')); 146 $this->linkDB->savedb($this->conf->get('path.page_cache'));
143 return true; 147 return true;
144 } 148 }
145 149
@@ -151,23 +155,21 @@ class Updater
151 */ 155 */
152 public function updateMethodConfigToJson() 156 public function updateMethodConfigToJson()
153 { 157 {
154 $conf = ConfigManager::getInstance();
155
156 // JSON config already exists, nothing to do. 158 // JSON config already exists, nothing to do.
157 if ($conf->getConfigIO() instanceof ConfigJson) { 159 if ($this->conf->getConfigIO() instanceof ConfigJson) {
158 return true; 160 return true;
159 } 161 }
160 162
161 $configPhp = new ConfigPhp(); 163 $configPhp = new ConfigPhp();
162 $configJson = new ConfigJson(); 164 $configJson = new ConfigJson();
163 $oldConfig = $configPhp->read($conf::$CONFIG_FILE . '.php'); 165 $oldConfig = $configPhp->read($this->conf->getConfigFile() . '.php');
164 rename($conf->getConfigFile(), $conf::$CONFIG_FILE . '.save.php'); 166 rename($this->conf->getConfigFileExt(), $this->conf->getConfigFile() . '.save.php');
165 $conf->setConfigIO($configJson); 167 $this->conf->setConfigIO($configJson);
166 $conf->reload(); 168 $this->conf->reload();
167 169
168 $legacyMap = array_flip(ConfigPhp::$LEGACY_KEYS_MAPPING); 170 $legacyMap = array_flip(ConfigPhp::$LEGACY_KEYS_MAPPING);
169 foreach (ConfigPhp::$ROOT_KEYS as $key) { 171 foreach (ConfigPhp::$ROOT_KEYS as $key) {
170 $conf->set($legacyMap[$key], $oldConfig[$key]); 172 $this->conf->set($legacyMap[$key], $oldConfig[$key]);
171 } 173 }
172 174
173 // Set sub config keys (config and plugins) 175 // Set sub config keys (config and plugins)
@@ -179,12 +181,12 @@ class Updater
179 } else { 181 } else {
180 $configKey = $sub .'.'. $key; 182 $configKey = $sub .'.'. $key;
181 } 183 }
182 $conf->set($configKey, $value); 184 $this->conf->set($configKey, $value);
183 } 185 }
184 } 186 }
185 187
186 try{ 188 try{
187 $conf->write($this->isLoggedIn); 189 $this->conf->write($this->isLoggedIn);
188 return true; 190 return true;
189 } catch (IOException $e) { 191 } catch (IOException $e) {
190 error_log($e->getMessage()); 192 error_log($e->getMessage());
@@ -202,12 +204,11 @@ class Updater
202 */ 204 */
203 public function escapeUnescapedConfig() 205 public function escapeUnescapedConfig()
204 { 206 {
205 $conf = ConfigManager::getInstance();
206 try { 207 try {
207 $conf->set('general.title', escape($conf->get('general.title'))); 208 $this->conf->set('general.title', escape($this->conf->get('general.title')));
208 $conf->set('general.header_link', escape($conf->get('general.header_link'))); 209 $this->conf->set('general.header_link', escape($this->conf->get('general.header_link')));
209 $conf->set('extras.redirector', escape($conf->get('extras.redirector'))); 210 $this->conf->set('extras.redirector', escape($this->conf->get('extras.redirector')));
210 $conf->write($this->isLoggedIn); 211 $this->conf->write($this->isLoggedIn);
211 } catch (Exception $e) { 212 } catch (Exception $e) {
212 error_log($e->getMessage()); 213 error_log($e->getMessage());
213 return false; 214 return false;
diff --git a/application/config/ConfigManager.php b/application/config/ConfigManager.php
index c0482cf3..5aafc89d 100644
--- a/application/config/ConfigManager.php
+++ b/application/config/ConfigManager.php
@@ -2,13 +2,13 @@
2 2
3// FIXME! Namespaces... 3// FIXME! Namespaces...
4require_once 'ConfigIO.php'; 4require_once 'ConfigIO.php';
5require_once 'ConfigPhp.php';
6require_once 'ConfigJson.php'; 5require_once 'ConfigJson.php';
6require_once 'ConfigPhp.php';
7 7
8/** 8/**
9 * Class ConfigManager 9 * Class ConfigManager
10 * 10 *
11 * Singleton, manages all Shaarli's settings. 11 * Manages all Shaarli's settings.
12 * See the documentation for more information on settings: 12 * See the documentation for more information on settings:
13 * - doc/Shaarli-configuration.html 13 * - doc/Shaarli-configuration.html
14 * - https://github.com/shaarli/Shaarli/wiki/Shaarli-configuration 14 * - https://github.com/shaarli/Shaarli/wiki/Shaarli-configuration
@@ -16,19 +16,14 @@ require_once 'ConfigJson.php';
16class ConfigManager 16class ConfigManager
17{ 17{
18 /** 18 /**
19 * @var ConfigManager instance. 19 * @var string Flag telling a setting is not found.
20 */ 20 */
21 protected static $instance = null; 21 protected static $NOT_FOUND = 'NOT_FOUND';
22 22
23 /** 23 /**
24 * @var string Config folder. 24 * @var string Config folder.
25 */ 25 */
26 public static $CONFIG_FILE = 'data/config'; 26 protected $configFile;
27
28 /**
29 * @var string Flag telling a setting is not found.
30 */
31 protected static $NOT_FOUND = 'NOT_FOUND';
32 27
33 /** 28 /**
34 * @var array Loaded config array. 29 * @var array Loaded config array.
@@ -41,37 +36,20 @@ class ConfigManager
41 protected $configIO; 36 protected $configIO;
42 37
43 /** 38 /**
44 * Private constructor: new instances not allowed. 39 * Constructor.
45 */ 40 */
46 private function __construct() {} 41 public function __construct($configFile = 'data/config')
47
48 /**
49 * Cloning isn't allowed either.
50 */
51 private function __clone() {}
52
53 /**
54 * Return existing instance of PluginManager, or create it.
55 *
56 * @return ConfigManager instance.
57 */
58 public static function getInstance()
59 { 42 {
60 if (!(self::$instance instanceof self)) { 43 $this->configFile = $configFile;
61 self::$instance = new self(); 44 $this->initialize();
62 self::$instance->initialize();
63 }
64
65 return self::$instance;
66 } 45 }
67 46
68 /** 47 /**
69 * Reset the ConfigManager instance. 48 * Reset the ConfigManager instance.
70 */ 49 */
71 public static function reset() 50 public function reset()
72 { 51 {
73 self::$instance = null; 52 $this->initialize();
74 return self::getInstance();
75 } 53 }
76 54
77 /** 55 /**
@@ -87,10 +65,10 @@ class ConfigManager
87 */ 65 */
88 protected function initialize() 66 protected function initialize()
89 { 67 {
90 if (! file_exists(self::$CONFIG_FILE .'.php')) { 68 if (file_exists($this->configFile . '.php')) {
91 $this->configIO = new ConfigJson();
92 } else {
93 $this->configIO = new ConfigPhp(); 69 $this->configIO = new ConfigPhp();
70 } else {
71 $this->configIO = new ConfigJson();
94 } 72 }
95 $this->load(); 73 $this->load();
96 } 74 }
@@ -100,7 +78,7 @@ class ConfigManager
100 */ 78 */
101 protected function load() 79 protected function load()
102 { 80 {
103 $this->loadedConfig = $this->configIO->read($this->getConfigFile()); 81 $this->loadedConfig = $this->configIO->read($this->getConfigFileExt());
104 $this->setDefaultValues(); 82 $this->setDefaultValues();
105 } 83 }
106 84
@@ -213,7 +191,7 @@ class ConfigManager
213 ); 191 );
214 192
215 // Only logged in user can alter config. 193 // Only logged in user can alter config.
216 if (is_file(self::$CONFIG_FILE) && !$isLoggedIn) { 194 if (is_file($this->getConfigFileExt()) && !$isLoggedIn) {
217 throw new UnauthorizedConfigException(); 195 throw new UnauthorizedConfigException();
218 } 196 }
219 197
@@ -224,17 +202,37 @@ class ConfigManager
224 } 202 }
225 } 203 }
226 204
227 return $this->configIO->write($this->getConfigFile(), $this->loadedConfig); 205 return $this->configIO->write($this->getConfigFileExt(), $this->loadedConfig);
228 } 206 }
229 207
230 /** 208 /**
231 * Get the configuration file path. 209 * Set the config file path (without extension).
232 * 210 *
233 * @return string Config file path. 211 * @param string $configFile File path.
212 */
213 public function setConfigFile($configFile)
214 {
215 $this->configFile = $configFile;
216 }
217
218 /**
219 * Return the configuration file path (without extension).
220 *
221 * @return string Config path.
234 */ 222 */
235 public function getConfigFile() 223 public function getConfigFile()
236 { 224 {
237 return self::$CONFIG_FILE . $this->configIO->getExtension(); 225 return $this->configFile;
226 }
227
228 /**
229 * Get the configuration file path with its extension.
230 *
231 * @return string Config file path.
232 */
233 public function getConfigFileExt()
234 {
235 return $this->configFile . $this->configIO->getExtension();
238 } 236 }
239 237
240 /** 238 /**
@@ -302,7 +300,7 @@ class ConfigManager
302 $this->setEmpty('path.page_cache', 'pagecache'); 300 $this->setEmpty('path.page_cache', 'pagecache');
303 301
304 $this->setEmpty('security.ban_after', 4); 302 $this->setEmpty('security.ban_after', 4);
305 $this->setEmpty('security.ban_after', 1800); 303 $this->setEmpty('security.ban_duration', 1800);
306 $this->setEmpty('security.session_protection_disabled', false); 304 $this->setEmpty('security.session_protection_disabled', false);
307 305
308 $this->setEmpty('general.check_updates', false); 306 $this->setEmpty('general.check_updates', false);
diff --git a/index.php b/index.php
index ac4a680d..d061f912 100644
--- a/index.php
+++ b/index.php
@@ -48,6 +48,8 @@ error_reporting(E_ALL^E_WARNING);
48require_once 'application/ApplicationUtils.php'; 48require_once 'application/ApplicationUtils.php';
49require_once 'application/Cache.php'; 49require_once 'application/Cache.php';
50require_once 'application/CachedPage.php'; 50require_once 'application/CachedPage.php';
51require_once 'application/config/ConfigManager.php';
52require_once 'application/config/ConfigPlugin.php';
51require_once 'application/FeedBuilder.php'; 53require_once 'application/FeedBuilder.php';
52require_once 'application/FileUtils.php'; 54require_once 'application/FileUtils.php';
53require_once 'application/HttpUtils.php'; 55require_once 'application/HttpUtils.php';
@@ -59,8 +61,6 @@ require_once 'application/PageBuilder.php';
59require_once 'application/TimeZone.php'; 61require_once 'application/TimeZone.php';
60require_once 'application/Url.php'; 62require_once 'application/Url.php';
61require_once 'application/Utils.php'; 63require_once 'application/Utils.php';
62require_once 'application/config/ConfigManager.php';
63require_once 'application/config/ConfigPlugin.php';
64require_once 'application/PluginManager.php'; 64require_once 'application/PluginManager.php';
65require_once 'application/Router.php'; 65require_once 'application/Router.php';
66require_once 'application/Updater.php'; 66require_once 'application/Updater.php';
@@ -105,13 +105,13 @@ if (isset($_COOKIE['shaarli']) && !is_session_id_valid($_COOKIE['shaarli'])) {
105 $_COOKIE['shaarli'] = session_id(); 105 $_COOKIE['shaarli'] = session_id();
106} 106}
107 107
108$conf = ConfigManager::getInstance(); 108$conf = new ConfigManager();
109$conf->setEmpty('general.timezone', date_default_timezone_get()); 109$conf->setEmpty('general.timezone', date_default_timezone_get());
110$conf->setEmpty('general.title', 'Shared links on '. escape(index_url($_SERVER))); 110$conf->setEmpty('general.title', 'Shared links on '. escape(index_url($_SERVER)));
111RainTPL::$tpl_dir = $conf->get('path.raintpl_tpl'); // template directory 111RainTPL::$tpl_dir = $conf->get('path.raintpl_tpl'); // template directory
112RainTPL::$cache_dir = $conf->get('path.raintpl_tmp'); // cache directory 112RainTPL::$cache_dir = $conf->get('path.raintpl_tmp'); // cache directory
113 113
114$pluginManager = PluginManager::getInstance(); 114$pluginManager = new PluginManager($conf);
115$pluginManager->load($conf->get('general.enabled_plugins')); 115$pluginManager->load($conf->get('general.enabled_plugins'));
116 116
117date_default_timezone_set($conf->get('general.timezone', 'UTC')); 117date_default_timezone_set($conf->get('general.timezone', 'UTC'));
@@ -133,9 +133,9 @@ header("Cache-Control: no-store, no-cache, must-revalidate");
133header("Cache-Control: post-check=0, pre-check=0", false); 133header("Cache-Control: post-check=0, pre-check=0", false);
134header("Pragma: no-cache"); 134header("Pragma: no-cache");
135 135
136if (! is_file($conf->getConfigFile())) { 136if (! is_file($conf->getConfigFileExt())) {
137 // Ensure Shaarli has proper access to its resources 137 // Ensure Shaarli has proper access to its resources
138 $errors = ApplicationUtils::checkResourcePermissions(); 138 $errors = ApplicationUtils::checkResourcePermissions($conf);
139 139
140 if ($errors != array()) { 140 if ($errors != array()) {
141 $message = '<p>Insufficient permissions:</p><ul>'; 141 $message = '<p>Insufficient permissions:</p><ul>';
@@ -151,7 +151,7 @@ if (! is_file($conf->getConfigFile())) {
151 } 151 }
152 152
153 // Display the installation form if no existing config is found 153 // Display the installation form if no existing config is found
154 install(); 154 install($conf);
155} 155}
156 156
157// a token depending of deployment salt, user password, and the current ip 157// a token depending of deployment salt, user password, and the current ip
@@ -163,13 +163,15 @@ if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
163} 163}
164header('Content-Type: text/html; charset=utf-8'); // We use UTF-8 for proper international characters handling. 164header('Content-Type: text/html; charset=utf-8'); // We use UTF-8 for proper international characters handling.
165 165
166//================================================================================================== 166/**
167// Checking session state (i.e. is the user still logged in) 167 * Checking session state (i.e. is the user still logged in)
168//================================================================================================== 168 *
169 169 * @param ConfigManager $conf The configuration manager.
170function setup_login_state() { 170 *
171 $conf = ConfigManager::getInstance(); 171 * @return bool: true if the user is logged in, false otherwise.
172 172 */
173function setup_login_state($conf)
174{
173 if ($conf->get('extras.open_shaarli')) { 175 if ($conf->get('extras.open_shaarli')) {
174 return true; 176 return true;
175 } 177 }
@@ -183,7 +185,7 @@ function setup_login_state() {
183 $_COOKIE['shaarli_staySignedIn']===STAY_SIGNED_IN_TOKEN && 185 $_COOKIE['shaarli_staySignedIn']===STAY_SIGNED_IN_TOKEN &&
184 !$loginFailure) 186 !$loginFailure)
185 { 187 {
186 fillSessionInfo(); 188 fillSessionInfo($conf);
187 $userIsLoggedIn = true; 189 $userIsLoggedIn = true;
188 } 190 }
189 // If session does not exist on server side, or IP address has changed, or session has expired, logout. 191 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
@@ -207,14 +209,16 @@ function setup_login_state() {
207 209
208 return $userIsLoggedIn; 210 return $userIsLoggedIn;
209} 211}
210$userIsLoggedIn = setup_login_state(); 212$userIsLoggedIn = setup_login_state($conf);
211 213
212// ------------------------------------------------------------------------------------------ 214/**
213// PubSubHubbub protocol support (if enabled) [UNTESTED] 215 * PubSubHubbub protocol support (if enabled) [UNTESTED]
214// (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ ) 216 * (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
215function pubsubhub() 217 *
218 * @param ConfigManager $conf Configuration Manager instance.
219 */
220function pubsubhub($conf)
216{ 221{
217 $conf = ConfigManager::getInstance();
218 $pshUrl = $conf->get('config.PUBSUBHUB_URL'); 222 $pshUrl = $conf->get('config.PUBSUBHUB_URL');
219 if (!empty($pshUrl)) 223 if (!empty($pshUrl))
220 { 224 {
@@ -241,27 +245,39 @@ function allIPs()
241 return $ip; 245 return $ip;
242} 246}
243 247
244function fillSessionInfo() { 248/**
245 $conf = ConfigManager::getInstance(); 249 * Load user session.
250 *
251 * @param ConfigManager $conf Configuration Manager instance.
252 */
253function fillSessionInfo($conf)
254{
246 $_SESSION['uid'] = sha1(uniqid('',true).'_'.mt_rand()); // Generate unique random number (different than phpsessionid) 255 $_SESSION['uid'] = sha1(uniqid('',true).'_'.mt_rand()); // Generate unique random number (different than phpsessionid)
247 $_SESSION['ip']=allIPs(); // We store IP address(es) of the client to make sure session is not hijacked. 256 $_SESSION['ip']=allIPs(); // We store IP address(es) of the client to make sure session is not hijacked.
248 $_SESSION['username']= $conf->get('credentials.login'); 257 $_SESSION['username']= $conf->get('credentials.login');
249 $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // Set session expiration. 258 $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // Set session expiration.
250} 259}
251 260
252// Check that user/password is correct. 261/**
253function check_auth($login,$password) 262 * Check that user/password is correct.
263 *
264 * @param string $login Username
265 * @param string $password User password
266 * @param ConfigManager $conf Configuration Manager instance.
267 *
268 * @return bool: authentication successful or not.
269 */
270function check_auth($login, $password, $conf)
254{ 271{
255 $conf = ConfigManager::getInstance();
256 $hash = sha1($password . $login . $conf->get('credentials.salt')); 272 $hash = sha1($password . $login . $conf->get('credentials.salt'));
257 if ($login == $conf->get('credentials.login') && $hash == $conf->get('credentials.hash')) 273 if ($login == $conf->get('credentials.login') && $hash == $conf->get('credentials.hash'))
258 { // Login/password is correct. 274 { // Login/password is correct.
259 fillSessionInfo(); 275 fillSessionInfo($conf);
260 logm($conf->get('path.log'), $_SERVER['REMOTE_ADDR'], 'Login successful'); 276 logm($conf->get('path.log'), $_SERVER['REMOTE_ADDR'], 'Login successful');
261 return True; 277 return true;
262 } 278 }
263 logm($conf->get('path.log'), $_SERVER['REMOTE_ADDR'], 'Login failed for user '.$login); 279 logm($conf->get('path.log'), $_SERVER['REMOTE_ADDR'], 'Login failed for user '.$login);
264 return False; 280 return false;
265} 281}
266 282
267// Returns true if the user is logged in. 283// Returns true if the user is logged in.
@@ -294,10 +310,13 @@ if (!is_file($conf->get('path.ban_file', 'data/ipbans.php'))) {
294 ); 310 );
295} 311}
296include $conf->get('path.ban_file', 'data/ipbans.php'); 312include $conf->get('path.ban_file', 'data/ipbans.php');
297// Signal a failed login. Will ban the IP if too many failures: 313/**
298function ban_loginFailed() 314 * Signal a failed login. Will ban the IP if too many failures:
315 *
316 * @param ConfigManager $conf Configuration Manager instance.
317 */
318function ban_loginFailed($conf)
299{ 319{
300 $conf = ConfigManager::getInstance();
301 $ip = $_SERVER['REMOTE_ADDR']; 320 $ip = $_SERVER['REMOTE_ADDR'];
302 $gb = $GLOBALS['IPBANS']; 321 $gb = $GLOBALS['IPBANS'];
303 if (!isset($gb['FAILURES'][$ip])) $gb['FAILURES'][$ip]=0; 322 if (!isset($gb['FAILURES'][$ip])) $gb['FAILURES'][$ip]=0;
@@ -314,10 +333,13 @@ function ban_loginFailed()
314 ); 333 );
315} 334}
316 335
317// Signals a successful login. Resets failed login counter. 336/**
318function ban_loginOk() 337 * Signals a successful login. Resets failed login counter.
338 *
339 * @param ConfigManager $conf Configuration Manager instance.
340 */
341function ban_loginOk($conf)
319{ 342{
320 $conf = ConfigManager::getInstance();
321 $ip = $_SERVER['REMOTE_ADDR']; 343 $ip = $_SERVER['REMOTE_ADDR'];
322 $gb = $GLOBALS['IPBANS']; 344 $gb = $GLOBALS['IPBANS'];
323 unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]); 345 unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]);
@@ -328,10 +350,15 @@ function ban_loginOk()
328 ); 350 );
329} 351}
330 352
331// Checks if the user CAN login. If 'true', the user can try to login. 353/**
332function ban_canLogin() 354 * Checks if the user CAN login. If 'true', the user can try to login.
355 *
356 * @param ConfigManager $conf Configuration Manager instance.
357 *
358 * @return bool: true if the user is allowed to login.
359 */
360function ban_canLogin($conf)
333{ 361{
334 $conf = ConfigManager::getInstance();
335 $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS']; 362 $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS'];
336 if (isset($gb['BANS'][$ip])) 363 if (isset($gb['BANS'][$ip]))
337 { 364 {
@@ -355,10 +382,12 @@ function ban_canLogin()
355// Process login form: Check if login/password is correct. 382// Process login form: Check if login/password is correct.
356if (isset($_POST['login'])) 383if (isset($_POST['login']))
357{ 384{
358 if (!ban_canLogin()) die('I said: NO. You are banned for the moment. Go away.'); 385 if (!ban_canLogin($conf)) die('I said: NO. You are banned for the moment. Go away.');
359 if (isset($_POST['password']) && tokenOk($_POST['token']) && (check_auth($_POST['login'], $_POST['password']))) 386 if (isset($_POST['password'])
360 { // Login/password is OK. 387 && tokenOk($_POST['token'])
361 ban_loginOk(); 388 && (check_auth($_POST['login'], $_POST['password'], $conf))
389 ) { // Login/password is OK.
390 ban_loginOk($conf);
362 // If user wants to keep the session cookie even after the browser closes: 391 // If user wants to keep the session cookie even after the browser closes:
363 if (!empty($_POST['longlastingsession'])) 392 if (!empty($_POST['longlastingsession']))
364 { 393 {
@@ -406,7 +435,7 @@ if (isset($_POST['login']))
406 } 435 }
407 else 436 else
408 { 437 {
409 ban_loginFailed(); 438 ban_loginFailed($conf);
410 $redir = '&username='. $_POST['login']; 439 $redir = '&username='. $_POST['login'];
411 if (isset($_GET['post'])) { 440 if (isset($_GET['post'])) {
412 $redir .= '&post=' . urlencode($_GET['post']); 441 $redir .= '&post=' . urlencode($_GET['post']);
@@ -454,10 +483,15 @@ function getMaxFileSize()
454// Token should be used in any form which acts on data (create,update,delete,import...). 483// Token should be used in any form which acts on data (create,update,delete,import...).
455if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are attached to the session. 484if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are attached to the session.
456 485
457// Returns a token. 486/**
458function getToken() 487 * Returns a token.
488 *
489 * @param ConfigManager $conf Configuration Manager instance.
490 *
491 * @return string token.
492 */
493function getToken($conf)
459{ 494{
460 $conf = ConfigManager::getInstance();
461 $rnd = sha1(uniqid('', true) .'_'. mt_rand() . $conf->get('credentials.salt')); // We generate a random string. 495 $rnd = sha1(uniqid('', true) .'_'. mt_rand() . $conf->get('credentials.salt')); // We generate a random string.
462 $_SESSION['tokens'][$rnd]=1; // Store it on the server side. 496 $_SESSION['tokens'][$rnd]=1; // Store it on the server side.
463 return $rnd; 497 return $rnd;
@@ -475,12 +509,14 @@ function tokenOk($token)
475 return false; // Wrong token, or already used. 509 return false; // Wrong token, or already used.
476} 510}
477 511
478// ------------------------------------------------------------------------------------------ 512/**
479// Daily RSS feed: 1 RSS entry per day giving all the links on that day. 513 * Daily RSS feed: 1 RSS entry per day giving all the links on that day.
480// Gives the last 7 days (which have links). 514 * Gives the last 7 days (which have links).
481// This RSS feed cannot be filtered. 515 * This RSS feed cannot be filtered.
482function showDailyRSS() { 516 *
483 $conf = ConfigManager::getInstance(); 517 * @param ConfigManager $conf Configuration Manager instance.
518 */
519function showDailyRSS($conf) {
484 // Cache system 520 // Cache system
485 $query = $_SERVER['QUERY_STRING']; 521 $query = $_SERVER['QUERY_STRING'];
486 $cache = new CachedPage( 522 $cache = new CachedPage(
@@ -555,7 +591,7 @@ function showDailyRSS() {
555 foreach ($linkdates as $linkdate) { 591 foreach ($linkdates as $linkdate) {
556 $l = $LINKSDB[$linkdate]; 592 $l = $LINKSDB[$linkdate];
557 $l['formatedDescription'] = format_description($l['description'], $conf->get('extras.redirector')); 593 $l['formatedDescription'] = format_description($l['description'], $conf->get('extras.redirector'));
558 $l['thumbnail'] = thumbnail($l['url']); 594 $l['thumbnail'] = thumbnail($conf, $l['url']);
559 $l_date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $l['linkdate']); 595 $l_date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $l['linkdate']);
560 $l['timestamp'] = $l_date->getTimestamp(); 596 $l['timestamp'] = $l_date->getTimestamp();
561 if (startsWith($l['url'], '?')) { 597 if (startsWith($l['url'], '?')) {
@@ -586,12 +622,13 @@ function showDailyRSS() {
586/** 622/**
587 * Show the 'Daily' page. 623 * Show the 'Daily' page.
588 * 624 *
589 * @param PageBuilder $pageBuilder Template engine wrapper. 625 * @param PageBuilder $pageBuilder Template engine wrapper.
590 * @param LinkDB $LINKSDB LinkDB instance. 626 * @param LinkDB $LINKSDB LinkDB instance.
627 * @param ConfigManager $conf Configuration Manager instance.
628 * @param PluginManager $pluginManager Plugin Manager instane.
591 */ 629 */
592function showDaily($pageBuilder, $LINKSDB) 630function showDaily($pageBuilder, $LINKSDB, $conf, $pluginManager)
593{ 631{
594 $conf = ConfigManager::getInstance();
595 $day=date('Ymd',strtotime('-1 day')); // Yesterday, in format YYYYMMDD. 632 $day=date('Ymd',strtotime('-1 day')); // Yesterday, in format YYYYMMDD.
596 if (isset($_GET['day'])) $day=$_GET['day']; 633 if (isset($_GET['day'])) $day=$_GET['day'];
597 634
@@ -621,7 +658,7 @@ function showDaily($pageBuilder, $LINKSDB)
621 uasort($taglist, 'strcasecmp'); 658 uasort($taglist, 'strcasecmp');
622 $linksToDisplay[$key]['taglist']=$taglist; 659 $linksToDisplay[$key]['taglist']=$taglist;
623 $linksToDisplay[$key]['formatedDescription'] = format_description($link['description'], $conf->get('extras.redirector')); 660 $linksToDisplay[$key]['formatedDescription'] = format_description($link['description'], $conf->get('extras.redirector'));
624 $linksToDisplay[$key]['thumbnail'] = thumbnail($link['url']); 661 $linksToDisplay[$key]['thumbnail'] = thumbnail($conf, $link['url']);
625 $date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $link['linkdate']); 662 $date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $link['linkdate']);
626 $linksToDisplay[$key]['timestamp'] = $date->getTimestamp(); 663 $linksToDisplay[$key]['timestamp'] = $date->getTimestamp();
627 } 664 }
@@ -656,7 +693,7 @@ function showDaily($pageBuilder, $LINKSDB)
656 'previousday' => $previousday, 693 'previousday' => $previousday,
657 'nextday' => $nextday, 694 'nextday' => $nextday,
658 ); 695 );
659 $pluginManager = PluginManager::getInstance(); 696
660 $pluginManager->executeHooks('render_daily', $data, array('loggedin' => isLoggedIn())); 697 $pluginManager->executeHooks('render_daily', $data, array('loggedin' => isLoggedIn()));
661 698
662 foreach ($data as $key => $value) { 699 foreach ($data as $key => $value) {
@@ -667,18 +704,27 @@ function showDaily($pageBuilder, $LINKSDB)
667 exit; 704 exit;
668} 705}
669 706
670// Renders the linklist 707/**
671function showLinkList($PAGE, $LINKSDB) { 708 * Renders the linklist
672 buildLinkList($PAGE,$LINKSDB); // Compute list of links to display 709 *
710 * @param pageBuilder $PAGE pageBuilder instance.
711 * @param LinkDB $LINKSDB LinkDB instance.
712 * @param ConfigManager $conf Configuration Manager instance.
713 * @param PluginManager $pluginManager Plugin Manager instance.
714 */
715function showLinkList($PAGE, $LINKSDB, $conf, $pluginManager) {
716 buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager); // Compute list of links to display
673 $PAGE->renderPage('linklist'); 717 $PAGE->renderPage('linklist');
674} 718}
675 719
676 720/**
677// ------------------------------------------------------------------------------------------ 721 * Render HTML page (according to URL parameters and user rights)
678// Render HTML page (according to URL parameters and user rights) 722 *
679function renderPage() 723 * @param ConfigManager $conf Configuration Manager instance.
724 * @param PluginManager $pluginManager Plugin Manager instance,
725 */
726function renderPage($conf, $pluginManager)
680{ 727{
681 $conf = ConfigManager::getInstance();
682 $LINKSDB = new LinkDB( 728 $LINKSDB = new LinkDB(
683 $conf->get('path.datastore'), 729 $conf->get('path.datastore'),
684 isLoggedIn(), 730 isLoggedIn(),
@@ -690,6 +736,7 @@ function renderPage()
690 $updater = new Updater( 736 $updater = new Updater(
691 read_updates_file($conf->get('path.updates')), 737 read_updates_file($conf->get('path.updates')),
692 $LINKSDB, 738 $LINKSDB,
739 $conf,
693 isLoggedIn() 740 isLoggedIn()
694 ); 741 );
695 try { 742 try {
@@ -705,7 +752,7 @@ function renderPage()
705 die($e->getMessage()); 752 die($e->getMessage());
706 } 753 }
707 754
708 $PAGE = new PageBuilder(); 755 $PAGE = new PageBuilder($conf);
709 $PAGE->assign('linkcount', count($LINKSDB)); 756 $PAGE->assign('linkcount', count($LINKSDB));
710 $PAGE->assign('privateLinkcount', count_private($LINKSDB)); 757 $PAGE->assign('privateLinkcount', count_private($LINKSDB));
711 758
@@ -720,7 +767,7 @@ function renderPage()
720 'header', 767 'header',
721 'footer', 768 'footer',
722 ); 769 );
723 $pluginManager = PluginManager::getInstance(); 770
724 foreach($common_hooks as $name) { 771 foreach($common_hooks as $name) {
725 $plugin_data = array(); 772 $plugin_data = array();
726 $pluginManager->executeHooks('render_' . $name, $plugin_data, 773 $pluginManager->executeHooks('render_' . $name, $plugin_data,
@@ -736,7 +783,7 @@ function renderPage()
736 if ($targetPage == Router::$PAGE_LOGIN) 783 if ($targetPage == Router::$PAGE_LOGIN)
737 { 784 {
738 if ($conf->get('extras.open_shaarli')) { header('Location: ?'); exit; } // No need to login for open Shaarli 785 if ($conf->get('extras.open_shaarli')) { header('Location: ?'); exit; } // No need to login for open Shaarli
739 $token=''; if (ban_canLogin()) $token=getToken(); // Do not waste token generation if not useful. 786 $token=''; if (ban_canLogin($conf)) $token=getToken($conf); // Do not waste token generation if not useful.
740 $PAGE->assign('token',$token); 787 $PAGE->assign('token',$token);
741 if (isset($_GET['username'])) { 788 if (isset($_GET['username'])) {
742 $PAGE->assign('username', escape($_GET['username'])); 789 $PAGE->assign('username', escape($_GET['username']));
@@ -765,7 +812,7 @@ function renderPage()
765 foreach($links as $link) 812 foreach($links as $link)
766 { 813 {
767 $permalink='?'.escape(smallhash($link['linkdate'])); 814 $permalink='?'.escape(smallhash($link['linkdate']));
768 $thumb=lazyThumbnail($link['url'],$permalink); 815 $thumb=lazyThumbnail($conf, $link['url'],$permalink);
769 if ($thumb!='') // Only output links which have a thumbnail. 816 if ($thumb!='') // Only output links which have a thumbnail.
770 { 817 {
771 $link['thumbnail']=$thumb; // Thumbnail HTML code. 818 $link['thumbnail']=$thumb; // Thumbnail HTML code.
@@ -837,7 +884,7 @@ function renderPage()
837 884
838 // Daily page. 885 // Daily page.
839 if ($targetPage == Router::$PAGE_DAILY) { 886 if ($targetPage == Router::$PAGE_DAILY) {
840 showDaily($PAGE, $LINKSDB); 887 showDaily($PAGE, $LINKSDB, $conf, $pluginManager);
841 } 888 }
842 889
843 // ATOM and RSS feed. 890 // ATOM and RSS feed.
@@ -870,7 +917,6 @@ function renderPage()
870 $data = $feedGenerator->buildData(); 917 $data = $feedGenerator->buildData();
871 918
872 // Process plugin hook. 919 // Process plugin hook.
873 $pluginManager = PluginManager::getInstance();
874 $pluginManager->executeHooks('render_feed', $data, array( 920 $pluginManager->executeHooks('render_feed', $data, array(
875 'loggedin' => isLoggedIn(), 921 'loggedin' => isLoggedIn(),
876 'target' => $targetPage, 922 'target' => $targetPage,
@@ -996,7 +1042,7 @@ function renderPage()
996 exit; 1042 exit;
997 } 1043 }
998 1044
999 showLinkList($PAGE, $LINKSDB); 1045 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager);
1000 if (isset($_GET['edit_link'])) { 1046 if (isset($_GET['edit_link'])) {
1001 header('Location: ?do=login&edit_link='. escape($_GET['edit_link'])); 1047 header('Location: ?do=login&edit_link='. escape($_GET['edit_link']));
1002 exit; 1048 exit;
@@ -1059,7 +1105,7 @@ function renderPage()
1059 } 1105 }
1060 else // show the change password form. 1106 else // show the change password form.
1061 { 1107 {
1062 $PAGE->assign('token',getToken()); 1108 $PAGE->assign('token',getToken($conf));
1063 $PAGE->renderPage('changepassword'); 1109 $PAGE->renderPage('changepassword');
1064 exit; 1110 exit;
1065 } 1111 }
@@ -1106,7 +1152,7 @@ function renderPage()
1106 } 1152 }
1107 else // Show the configuration form. 1153 else // Show the configuration form.
1108 { 1154 {
1109 $PAGE->assign('token',getToken()); 1155 $PAGE->assign('token',getToken($conf));
1110 $PAGE->assign('title', $conf->get('general.title')); 1156 $PAGE->assign('title', $conf->get('general.title'));
1111 $PAGE->assign('redirector', $conf->get('extras.redirector')); 1157 $PAGE->assign('redirector', $conf->get('extras.redirector'));
1112 list($timezone_form, $timezone_js) = generateTimeZoneForm($conf->get('general.timezone')); 1158 list($timezone_form, $timezone_js) = generateTimeZoneForm($conf->get('general.timezone'));
@@ -1125,7 +1171,7 @@ function renderPage()
1125 if ($targetPage == Router::$PAGE_CHANGETAG) 1171 if ($targetPage == Router::$PAGE_CHANGETAG)
1126 { 1172 {
1127 if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) { 1173 if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) {
1128 $PAGE->assign('token', getToken()); 1174 $PAGE->assign('token', getToken($conf));
1129 $PAGE->assign('tags', $LINKSDB->allTags()); 1175 $PAGE->assign('tags', $LINKSDB->allTags());
1130 $PAGE->renderPage('changetag'); 1176 $PAGE->renderPage('changetag');
1131 exit; 1177 exit;
@@ -1216,7 +1262,7 @@ function renderPage()
1216 1262
1217 $LINKSDB[$linkdate] = $link; 1263 $LINKSDB[$linkdate] = $link;
1218 $LINKSDB->savedb($conf->get('path.page_cache')); 1264 $LINKSDB->savedb($conf->get('path.page_cache'));
1219 pubsubhub(); 1265 pubsubhub($conf);
1220 1266
1221 // If we are called from the bookmarklet, we must close the popup: 1267 // If we are called from the bookmarklet, we must close the popup:
1222 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { 1268 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
@@ -1300,7 +1346,7 @@ function renderPage()
1300 $data = array( 1346 $data = array(
1301 'link' => $link, 1347 'link' => $link,
1302 'link_is_new' => false, 1348 'link_is_new' => false,
1303 'token' => getToken(), 1349 'token' => getToken($conf),
1304 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''), 1350 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1305 'tags' => $LINKSDB->allTags(), 1351 'tags' => $LINKSDB->allTags(),
1306 ); 1352 );
@@ -1367,7 +1413,7 @@ function renderPage()
1367 $data = array( 1413 $data = array(
1368 'link' => $link, 1414 'link' => $link,
1369 'link_is_new' => $link_is_new, 1415 'link_is_new' => $link_is_new,
1370 'token' => getToken(), // XSRF protection. 1416 'token' => getToken($conf), // XSRF protection.
1371 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''), 1417 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1372 'source' => (isset($_GET['source']) ? $_GET['source'] : ''), 1418 'source' => (isset($_GET['source']) ? $_GET['source'] : ''),
1373 'tags' => $LINKSDB->allTags(), 1419 'tags' => $LINKSDB->allTags(),
@@ -1445,7 +1491,7 @@ function renderPage()
1445 // -------- Show upload/import dialog: 1491 // -------- Show upload/import dialog:
1446 if ($targetPage == Router::$PAGE_IMPORT) 1492 if ($targetPage == Router::$PAGE_IMPORT)
1447 { 1493 {
1448 $PAGE->assign('token',getToken()); 1494 $PAGE->assign('token',getToken($conf));
1449 $PAGE->assign('maxfilesize',getMaxFileSize()); 1495 $PAGE->assign('maxfilesize',getMaxFileSize());
1450 $PAGE->renderPage('import'); 1496 $PAGE->renderPage('import');
1451 exit; 1497 exit;
@@ -1500,16 +1546,19 @@ function renderPage()
1500 } 1546 }
1501 1547
1502 // -------- Otherwise, simply display search form and links: 1548 // -------- Otherwise, simply display search form and links:
1503 showLinkList($PAGE, $LINKSDB); 1549 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager);
1504 exit; 1550 exit;
1505} 1551}
1506 1552
1507// ----------------------------------------------------------------------------------------------- 1553/**
1508// Process the import file form. 1554 * Process the import file form.
1509function importFile($LINKSDB) 1555 *
1556 * @param LinkDB $LINKSDB Loaded LinkDB instance.
1557 * @param ConfigManager $conf Configuration Manager instance.
1558 */
1559function importFile($LINKSDB, $conf)
1510{ 1560{
1511 if (!isLoggedIn()) { die('Not allowed.'); } 1561 if (!isLoggedIn()) { die('Not allowed.'); }
1512 $conf = ConfigManager::getInstance();
1513 1562
1514 $filename=$_FILES['filetoupload']['name']; 1563 $filename=$_FILES['filetoupload']['name'];
1515 $filesize=$_FILES['filetoupload']['size']; 1564 $filesize=$_FILES['filetoupload']['size'];
@@ -1594,12 +1643,13 @@ function importFile($LINKSDB)
1594 * Template for the list of links (<div id="linklist">) 1643 * Template for the list of links (<div id="linklist">)
1595 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html' 1644 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1596 * 1645 *
1597 * @param pageBuilder $PAGE pageBuilder instance. 1646 * @param pageBuilder $PAGE pageBuilder instance.
1598 * @param LinkDB $LINKSDB LinkDB instance. 1647 * @param LinkDB $LINKSDB LinkDB instance.
1648 * @param ConfigManager $conf Configuration Manager instance.
1649 * @param PluginManager $pluginManager Plugin Manager instance.
1599 */ 1650 */
1600function buildLinkList($PAGE,$LINKSDB) 1651function buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager)
1601{ 1652{
1602 $conf = ConfigManager::getInstance();
1603 // Used in templates 1653 // Used in templates
1604 $searchtags = !empty($_GET['searchtags']) ? escape($_GET['searchtags']) : ''; 1654 $searchtags = !empty($_GET['searchtags']) ? escape($_GET['searchtags']) : '';
1605 $searchterm = !empty($_GET['searchterm']) ? escape($_GET['searchterm']) : ''; 1655 $searchterm = !empty($_GET['searchterm']) ? escape($_GET['searchterm']) : '';
@@ -1674,7 +1724,7 @@ function buildLinkList($PAGE,$LINKSDB)
1674 $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl; 1724 $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl;
1675 } 1725 }
1676 1726
1677 $token = isLoggedIn() ? getToken() : ''; 1727 $token = isLoggedIn() ? getToken($conf) : '';
1678 1728
1679 // Fill all template fields. 1729 // Fill all template fields.
1680 $data = array( 1730 $data = array(
@@ -1695,7 +1745,6 @@ function buildLinkList($PAGE,$LINKSDB)
1695 $data['pagetitle'] = $conf->get('pagetitle'); 1745 $data['pagetitle'] = $conf->get('pagetitle');
1696 } 1746 }
1697 1747
1698 $pluginManager = PluginManager::getInstance();
1699 $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => isLoggedIn())); 1748 $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => isLoggedIn()));
1700 1749
1701 foreach ($data as $key => $value) { 1750 foreach ($data as $key => $value) {
@@ -1705,18 +1754,25 @@ function buildLinkList($PAGE,$LINKSDB)
1705 return; 1754 return;
1706} 1755}
1707 1756
1708// Compute the thumbnail for a link. 1757/**
1709// 1758 * Compute the thumbnail for a link.
1710// With a link to the original URL. 1759 *
1711// Understands various services (youtube.com...) 1760 * With a link to the original URL.
1712// Input: $url = URL for which the thumbnail must be found. 1761 * Understands various services (youtube.com...)
1713// $href = if provided, this URL will be followed instead of $url 1762 * Input: $url = URL for which the thumbnail must be found.
1714// Returns an associative array with thumbnail attributes (src,href,width,height,style,alt) 1763 * $href = if provided, this URL will be followed instead of $url
1715// Some of them may be missing. 1764 * Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
1716// Return an empty array if no thumbnail available. 1765 * Some of them may be missing.
1717function computeThumbnail($url,$href=false) 1766 * Return an empty array if no thumbnail available.
1767 *
1768 * @param ConfigManager $conf Configuration Manager instance.
1769 * @param string $url
1770 * @param string|bool $href
1771 *
1772 * @return array
1773 */
1774function computeThumbnail($conf, $url, $href = false)
1718{ 1775{
1719 $conf = ConfigManager::getInstance();
1720 if (!$conf->get('general.enable_thumbnails')) return array(); 1776 if (!$conf->get('general.enable_thumbnails')) return array();
1721 if ($href==false) $href=$url; 1777 if ($href==false) $href=$url;
1722 1778
@@ -1836,7 +1892,9 @@ function computeThumbnail($url,$href=false)
1836// Returns '' if no thumbnail available. 1892// Returns '' if no thumbnail available.
1837function thumbnail($url,$href=false) 1893function thumbnail($url,$href=false)
1838{ 1894{
1839 $t = computeThumbnail($url,$href); 1895 // FIXME!
1896 global $conf;
1897 $t = computeThumbnail($conf, $url,$href);
1840 if (count($t)==0) return ''; // Empty array = no thumbnail for this URL. 1898 if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
1841 1899
1842 $html='<a href="'.escape($t['href']).'"><img src="'.escape($t['src']).'"'; 1900 $html='<a href="'.escape($t['href']).'"><img src="'.escape($t['src']).'"';
@@ -1854,9 +1912,11 @@ function thumbnail($url,$href=false)
1854// Input: $url = URL for which the thumbnail must be found. 1912// Input: $url = URL for which the thumbnail must be found.
1855// $href = if provided, this URL will be followed instead of $url 1913// $href = if provided, this URL will be followed instead of $url
1856// Returns '' if no thumbnail available. 1914// Returns '' if no thumbnail available.
1857function lazyThumbnail($url,$href=false) 1915function lazyThumbnail($conf, $url,$href=false)
1858{ 1916{
1859 $t = computeThumbnail($url,$href); 1917 // FIXME!
1918 global $conf;
1919 $t = computeThumbnail($conf, $url,$href);
1860 if (count($t)==0) return ''; // Empty array = no thumbnail for this URL. 1920 if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
1861 1921
1862 $html='<a href="'.escape($t['href']).'">'; 1922 $html='<a href="'.escape($t['href']).'">';
@@ -1882,10 +1942,13 @@ function lazyThumbnail($url,$href=false)
1882} 1942}
1883 1943
1884 1944
1885// ----------------------------------------------------------------------------------------------- 1945/**
1886// Installation 1946 * Installation
1887// This function should NEVER be called if the file data/config.php exists. 1947 * This function should NEVER be called if the file data/config.php exists.
1888function install() 1948 *
1949 * @param ConfigManager $conf Configuration Manager instance.
1950 */
1951function install($conf)
1889{ 1952{
1890 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work. 1953 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1891 if (endsWith($_SERVER['HTTP_HOST'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705); 1954 if (endsWith($_SERVER['HTTP_HOST'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705);
@@ -1916,7 +1979,6 @@ function install()
1916 1979
1917 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword'])) 1980 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword']))
1918 { 1981 {
1919 $conf = ConfigManager::getInstance();
1920 $tz = 'UTC'; 1982 $tz = 'UTC';
1921 if (!empty($_POST['continent']) && !empty($_POST['city']) 1983 if (!empty($_POST['continent']) && !empty($_POST['city'])
1922 && isTimeZoneValid($_POST['continent'], $_POST['city']) 1984 && isTimeZoneValid($_POST['continent'], $_POST['city'])
@@ -1960,25 +2022,27 @@ function install()
1960 $timezone_html = '<tr><td><b>Timezone:</b></td><td>'.$timezone_form.'</td></tr>'; 2022 $timezone_html = '<tr><td><b>Timezone:</b></td><td>'.$timezone_form.'</td></tr>';
1961 } 2023 }
1962 2024
1963 $PAGE = new PageBuilder(); 2025 $PAGE = new PageBuilder($conf);
1964 $PAGE->assign('timezone_html',$timezone_html); 2026 $PAGE->assign('timezone_html',$timezone_html);
1965 $PAGE->assign('timezone_js',$timezone_js); 2027 $PAGE->assign('timezone_js',$timezone_js);
1966 $PAGE->renderPage('install'); 2028 $PAGE->renderPage('install');
1967 exit; 2029 exit;
1968} 2030}
1969 2031
1970/* Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL, 2032/**
1971 I have deported the thumbnail URL code generation here, otherwise this would slow down page generation. 2033 * Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
1972 The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail. 2034 * I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
1973 This function is called by passing the URL: 2035 * The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
1974 http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL] 2036 * This function is called by passing the URL:
1975 [URL] is the URL of the link (e.g. a flickr page) 2037 * http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
1976 [HMAC] is the signature for the [URL] (so that these URL cannot be forged). 2038 * [URL] is the URL of the link (e.g. a flickr page)
1977 The function below will fetch the image from the webservice and store it in the cache. 2039 * [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
1978*/ 2040 * The function below will fetch the image from the webservice and store it in the cache.
1979function genThumbnail() 2041 *
2042 * @param ConfigManager $conf Configuration Manager instance,
2043 */
2044function genThumbnail($conf)
1980{ 2045{
1981 $conf = ConfigManager::getInstance();
1982 // Make sure the parameters in the URL were generated by us. 2046 // Make sure the parameters in the URL were generated by us.
1983 $sign = hash_hmac('sha256', $_GET['url'], $conf->get('credentials.salt')); 2047 $sign = hash_hmac('sha256', $_GET['url'], $conf->get('credentials.salt'));
1984 if ($sign!=$_GET['hmac']) die('Naughty boy!'); 2048 if ($sign!=$_GET['hmac']) die('Naughty boy!');
@@ -2190,10 +2254,9 @@ function resizeImage($filepath)
2190 return true; 2254 return true;
2191} 2255}
2192 2256
2193if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=genthumbnail')) { genThumbnail(); exit; } // Thumbnail generation/cache does not need the link database. 2257if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=genthumbnail')) { genThumbnail($conf); exit; } // Thumbnail generation/cache does not need the link database.
2194if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) { showDailyRSS(); exit; } 2258if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) { showDailyRSS($conf); exit; }
2195if (!isset($_SESSION['LINKS_PER_PAGE'])) { 2259if (!isset($_SESSION['LINKS_PER_PAGE'])) {
2196 $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20); 2260 $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20);
2197} 2261}
2198renderPage(); 2262renderPage($conf, $pluginManager);
2199?>
diff --git a/tests/ApplicationUtilsTest.php b/tests/ApplicationUtilsTest.php
index f92412ba..3da72639 100644
--- a/tests/ApplicationUtilsTest.php
+++ b/tests/ApplicationUtilsTest.php
@@ -276,7 +276,7 @@ class ApplicationUtilsTest extends PHPUnit_Framework_TestCase
276 */ 276 */
277 public function testCheckCurrentResourcePermissions() 277 public function testCheckCurrentResourcePermissions()
278 { 278 {
279 $conf = ConfigManager::getInstance(); 279 $conf = new ConfigManager('');
280 $conf->set('path.thumbnails_cache', 'cache'); 280 $conf->set('path.thumbnails_cache', 'cache');
281 $conf->set('path.config', 'data/config.php'); 281 $conf->set('path.config', 'data/config.php');
282 $conf->set('path.data_dir', 'data'); 282 $conf->set('path.data_dir', 'data');
@@ -290,7 +290,7 @@ class ApplicationUtilsTest extends PHPUnit_Framework_TestCase
290 290
291 $this->assertEquals( 291 $this->assertEquals(
292 array(), 292 array(),
293 ApplicationUtils::checkResourcePermissions() 293 ApplicationUtils::checkResourcePermissions($conf)
294 ); 294 );
295 } 295 }
296 296
@@ -299,7 +299,7 @@ class ApplicationUtilsTest extends PHPUnit_Framework_TestCase
299 */ 299 */
300 public function testCheckCurrentResourcePermissionsErrors() 300 public function testCheckCurrentResourcePermissionsErrors()
301 { 301 {
302 $conf = ConfigManager::getInstance(); 302 $conf = new ConfigManager('');
303 $conf->set('path.thumbnails_cache', 'null/cache'); 303 $conf->set('path.thumbnails_cache', 'null/cache');
304 $conf->set('path.config', 'null/data/config.php'); 304 $conf->set('path.config', 'null/data/config.php');
305 $conf->set('path.data_dir', 'null/data'); 305 $conf->set('path.data_dir', 'null/data');
@@ -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() 325 ApplicationUtils::checkResourcePermissions($conf)
326 ); 326 );
327 } 327 }
328} 328}
diff --git a/tests/Updater/DummyUpdater.php b/tests/Updater/DummyUpdater.php
index 6724b203..a0be4413 100644
--- a/tests/Updater/DummyUpdater.php
+++ b/tests/Updater/DummyUpdater.php
@@ -11,13 +11,14 @@ class DummyUpdater extends Updater
11 /** 11 /**
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 LinkDB $linkDB LinkDB instance. 15 * @param LinkDB $linkDB LinkDB instance.
16 * @param boolean $isLoggedIn True if the user is logged in. 16 * @param ConfigManager $conf Configuration Manager instance.
17 * @param boolean $isLoggedIn True if the user is logged in.
17 */ 18 */
18 public function __construct($doneUpdates, $linkDB, $isLoggedIn) 19 public function __construct($doneUpdates, $linkDB, $conf, $isLoggedIn)
19 { 20 {
20 parent::__construct($doneUpdates, $linkDB, $isLoggedIn); 21 parent::__construct($doneUpdates, $linkDB, $conf, $isLoggedIn);
21 22
22 // Retrieve all update methods. 23 // Retrieve all update methods.
23 // For unit test, only retrieve final methods, 24 // For unit test, only retrieve final methods,
diff --git a/tests/Updater/UpdaterTest.php b/tests/Updater/UpdaterTest.php
index 04883a46..5ed2df6c 100644
--- a/tests/Updater/UpdaterTest.php
+++ b/tests/Updater/UpdaterTest.php
@@ -29,8 +29,7 @@ class UpdaterTest extends PHPUnit_Framework_TestCase
29 */ 29 */
30 public function setUp() 30 public function setUp()
31 { 31 {
32 ConfigManager::$CONFIG_FILE = self::$configFile; 32 $this->conf = new ConfigManager(self::$configFile);
33 $this->conf = ConfigManager::reset();
34 } 33 }
35 34
36 /** 35 /**
@@ -108,10 +107,10 @@ class UpdaterTest extends PHPUnit_Framework_TestCase
108 'updateMethodDummy3', 107 'updateMethodDummy3',
109 'updateMethodException', 108 'updateMethodException',
110 ); 109 );
111 $updater = new DummyUpdater($updates, array(), true); 110 $updater = new DummyUpdater($updates, array(), $this->conf, true);
112 $this->assertEquals(array(), $updater->update()); 111 $this->assertEquals(array(), $updater->update());
113 112
114 $updater = new DummyUpdater(array(), array(), false); 113 $updater = new DummyUpdater(array(), array(), $this->conf, false);
115 $this->assertEquals(array(), $updater->update()); 114 $this->assertEquals(array(), $updater->update());
116 } 115 }
117 116
@@ -126,7 +125,7 @@ class UpdaterTest extends PHPUnit_Framework_TestCase
126 'updateMethodDummy2', 125 'updateMethodDummy2',
127 'updateMethodDummy3', 126 'updateMethodDummy3',
128 ); 127 );
129 $updater = new DummyUpdater($updates, array(), true); 128 $updater = new DummyUpdater($updates, array(), $this->conf, true);
130 $this->assertEquals($expectedUpdates, $updater->update()); 129 $this->assertEquals($expectedUpdates, $updater->update());
131 } 130 }
132 131
@@ -142,7 +141,7 @@ class UpdaterTest extends PHPUnit_Framework_TestCase
142 ); 141 );
143 $expectedUpdate = array('updateMethodDummy2'); 142 $expectedUpdate = array('updateMethodDummy2');
144 143
145 $updater = new DummyUpdater($updates, array(), true); 144 $updater = new DummyUpdater($updates, array(), $this->conf, true);
146 $this->assertEquals($expectedUpdate, $updater->update()); 145 $this->assertEquals($expectedUpdate, $updater->update());
147 } 146 }
148 147
@@ -159,7 +158,7 @@ class UpdaterTest extends PHPUnit_Framework_TestCase
159 'updateMethodDummy3', 158 'updateMethodDummy3',
160 ); 159 );
161 160
162 $updater = new DummyUpdater($updates, array(), true); 161 $updater = new DummyUpdater($updates, array(), $this->conf, true);
163 $updater->update(); 162 $updater->update();
164 } 163 }
165 164
@@ -172,8 +171,8 @@ class UpdaterTest extends PHPUnit_Framework_TestCase
172 */ 171 */
173 public function testUpdateMergeDeprecatedConfig() 172 public function testUpdateMergeDeprecatedConfig()
174 { 173 {
175 ConfigManager::$CONFIG_FILE = 'tests/utils/config/configPhp'; 174 $this->conf->setConfigFile('tests/utils/config/configPhp');
176 $this->conf = $this->conf->reset(); 175 $this->conf->reset();
177 176
178 $optionsFile = 'tests/Updater/options.php'; 177 $optionsFile = 'tests/Updater/options.php';
179 $options = '<?php 178 $options = '<?php
@@ -181,10 +180,10 @@ $GLOBALS[\'privateLinkByDefault\'] = true;';
181 file_put_contents($optionsFile, $options); 180 file_put_contents($optionsFile, $options);
182 181
183 // tmp config file. 182 // tmp config file.
184 ConfigManager::$CONFIG_FILE = 'tests/Updater/config'; 183 $this->conf->setConfigFile('tests/Updater/config');
185 184
186 // merge configs 185 // merge configs
187 $updater = new Updater(array(), array(), true); 186 $updater = new Updater(array(), array(), $this->conf, true);
188 // This writes a new config file in tests/Updater/config.php 187 // This writes a new config file in tests/Updater/config.php
189 $updater->updateMethodMergeDeprecatedConfigFile(); 188 $updater->updateMethodMergeDeprecatedConfigFile();
190 189
@@ -193,7 +192,7 @@ $GLOBALS[\'privateLinkByDefault\'] = true;';
193 $this->assertTrue($this->conf->get('general.default_private_links')); 192 $this->assertTrue($this->conf->get('general.default_private_links'));
194 $this->assertFalse(is_file($optionsFile)); 193 $this->assertFalse(is_file($optionsFile));
195 // Delete the generated file. 194 // Delete the generated file.
196 unlink($this->conf->getConfigFile()); 195 unlink($this->conf->getConfigFileExt());
197 } 196 }
198 197
199 /** 198 /**
@@ -201,7 +200,7 @@ $GLOBALS[\'privateLinkByDefault\'] = true;';
201 */ 200 */
202 public function testMergeDeprecatedConfigNoFile() 201 public function testMergeDeprecatedConfigNoFile()
203 { 202 {
204 $updater = new Updater(array(), array(), true); 203 $updater = new Updater(array(), array(), $this->conf, true);
205 $updater->updateMethodMergeDeprecatedConfigFile(); 204 $updater->updateMethodMergeDeprecatedConfigFile();
206 205
207 $this->assertEquals('root', $this->conf->get('credentials.login')); 206 $this->assertEquals('root', $this->conf->get('credentials.login'));
@@ -216,7 +215,7 @@ $GLOBALS[\'privateLinkByDefault\'] = true;';
216 $refDB->write(self::$testDatastore); 215 $refDB->write(self::$testDatastore);
217 $linkDB = new LinkDB(self::$testDatastore, true, false); 216 $linkDB = new LinkDB(self::$testDatastore, true, false);
218 $this->assertEmpty($linkDB->filterSearch(array('searchtags' => 'exclude'))); 217 $this->assertEmpty($linkDB->filterSearch(array('searchtags' => 'exclude')));
219 $updater = new Updater(array(), $linkDB, true); 218 $updater = new Updater(array(), $linkDB, $this->conf, true);
220 $updater->updateMethodRenameDashTags(); 219 $updater->updateMethodRenameDashTags();
221 $this->assertNotEmpty($linkDB->filterSearch(array('searchtags' => 'exclude'))); 220 $this->assertNotEmpty($linkDB->filterSearch(array('searchtags' => 'exclude')));
222 } 221 }
@@ -227,29 +226,29 @@ $GLOBALS[\'privateLinkByDefault\'] = true;';
227 public function testConfigToJson() 226 public function testConfigToJson()
228 { 227 {
229 $configFile = 'tests/utils/config/configPhp'; 228 $configFile = 'tests/utils/config/configPhp';
230 ConfigManager::$CONFIG_FILE = $configFile; 229 $this->conf->setConfigFile($configFile);
231 $conf = ConfigManager::reset(); 230 $this->conf->reset();
232 231
233 // The ConfigIO is initialized with ConfigPhp. 232 // The ConfigIO is initialized with ConfigPhp.
234 $this->assertTrue($conf->getConfigIO() instanceof ConfigPhp); 233 $this->assertTrue($this->conf->getConfigIO() instanceof ConfigPhp);
235 234
236 $updater = new Updater(array(), array(), false); 235 $updater = new Updater(array(), array(), $this->conf, false);
237 $done = $updater->updateMethodConfigToJson(); 236 $done = $updater->updateMethodConfigToJson();
238 $this->assertTrue($done); 237 $this->assertTrue($done);
239 238
240 // The ConfigIO has been updated to ConfigJson. 239 // The ConfigIO has been updated to ConfigJson.
241 $this->assertTrue($conf->getConfigIO() instanceof ConfigJson); 240 $this->assertTrue($this->conf->getConfigIO() instanceof ConfigJson);
242 $this->assertTrue(file_exists($conf->getConfigFile())); 241 $this->assertTrue(file_exists($this->conf->getConfigFileExt()));
243 242
244 // Check JSON config data. 243 // Check JSON config data.
245 $conf->reload(); 244 $this->conf->reload();
246 $this->assertEquals('root', $conf->get('credentials.login')); 245 $this->assertEquals('root', $this->conf->get('credentials.login'));
247 $this->assertEquals('lala', $conf->get('extras.redirector')); 246 $this->assertEquals('lala', $this->conf->get('extras.redirector'));
248 $this->assertEquals('data/datastore.php', $conf->get('path.datastore')); 247 $this->assertEquals('data/datastore.php', $this->conf->get('path.datastore'));
249 $this->assertEquals('1', $conf->get('plugins.WALLABAG_VERSION')); 248 $this->assertEquals('1', $this->conf->get('plugins.WALLABAG_VERSION'));
250 249
251 rename($configFile . '.save.php', $configFile . '.php'); 250 rename($configFile . '.save.php', $configFile . '.php');
252 unlink($conf->getConfigFile()); 251 unlink($this->conf->getConfigFileExt());
253 } 252 }
254 253
255 /** 254 /**
@@ -257,11 +256,11 @@ $GLOBALS[\'privateLinkByDefault\'] = true;';
257 */ 256 */
258 public function testConfigToJsonNothingToDo() 257 public function testConfigToJsonNothingToDo()
259 { 258 {
260 $filetime = filemtime($this->conf->getConfigFile()); 259 $filetime = filemtime($this->conf->getConfigFileExt());
261 $updater = new Updater(array(), array(), false); 260 $updater = new Updater(array(), array(), $this->conf, false);
262 $done = $updater->updateMethodConfigToJson(); 261 $done = $updater->updateMethodConfigToJson();
263 $this->assertTrue($done); 262 $this->assertTrue($done);
264 $expected = filemtime($this->conf->getConfigFile()); 263 $expected = filemtime($this->conf->getConfigFileExt());
265 $this->assertEquals($expected, $filetime); 264 $this->assertEquals($expected, $filetime);
266 } 265 }
267} 266}
diff --git a/tests/config/ConfigManagerTest.php b/tests/config/ConfigManagerTest.php
index 9ff0f473..436e3d67 100644
--- a/tests/config/ConfigManagerTest.php
+++ b/tests/config/ConfigManagerTest.php
@@ -15,8 +15,7 @@ class ConfigManagerTest extends PHPUnit_Framework_TestCase
15 15
16 public function setUp() 16 public function setUp()
17 { 17 {
18 ConfigManager::$CONFIG_FILE = 'tests/utils/config/configJson'; 18 $this->conf = new ConfigManager('tests/utils/config/configJson');
19 $this->conf = ConfigManager::reset();
20 } 19 }
21 20
22 /** 21 /**
@@ -54,10 +53,10 @@ class ConfigManagerTest extends PHPUnit_Framework_TestCase
54 $this->conf->set('paramArray', array('foo' => 'bar')); 53 $this->conf->set('paramArray', array('foo' => 'bar'));
55 $this->conf->set('paramNull', null); 54 $this->conf->set('paramNull', null);
56 55
57 ConfigManager::$CONFIG_FILE = 'tests/utils/config/configTmp'; 56 $this->conf->setConfigFile('tests/utils/config/configTmp');
58 $this->conf->write(true); 57 $this->conf->write(true);
59 $this->conf->reload(); 58 $this->conf->reload();
60 unlink($this->conf->getConfigFile()); 59 unlink($this->conf->getConfigFileExt());
61 60
62 $this->assertEquals(42, $this->conf->get('paramInt')); 61 $this->assertEquals(42, $this->conf->get('paramInt'));
63 $this->assertEquals('value1', $this->conf->get('paramString')); 62 $this->assertEquals('value1', $this->conf->get('paramString'));
@@ -73,10 +72,10 @@ class ConfigManagerTest extends PHPUnit_Framework_TestCase
73 { 72 {
74 $this->conf->set('foo.bar.key.stuff', 'testSetWriteGetNested'); 73 $this->conf->set('foo.bar.key.stuff', 'testSetWriteGetNested');
75 74
76 ConfigManager::$CONFIG_FILE = 'tests/utils/config/configTmp'; 75 $this->conf->setConfigFile('tests/utils/config/configTmp');
77 $this->conf->write(true); 76 $this->conf->write(true);
78 $this->conf->reload(); 77 $this->conf->reload();
79 unlink($this->conf->getConfigFile()); 78 unlink($this->conf->getConfigFileExt());
80 79
81 $this->assertEquals('testSetWriteGetNested', $this->conf->get('foo.bar.key.stuff')); 80 $this->assertEquals('testSetWriteGetNested', $this->conf->get('foo.bar.key.stuff'));
82 } 81 }
@@ -110,8 +109,8 @@ class ConfigManagerTest extends PHPUnit_Framework_TestCase
110 */ 109 */
111 public function testWriteMissingParameter() 110 public function testWriteMissingParameter()
112 { 111 {
113 ConfigManager::$CONFIG_FILE = 'tests/utils/config/configTmp'; 112 $this->conf->setConfigFile('tests/utils/config/configTmp');
114 $this->assertFalse(file_exists($this->conf->getConfigFile())); 113 $this->assertFalse(file_exists($this->conf->getConfigFileExt()));
115 $this->conf->reload(); 114 $this->conf->reload();
116 115
117 $this->conf->write(true); 116 $this->conf->write(true);
@@ -151,10 +150,9 @@ class ConfigManagerTest extends PHPUnit_Framework_TestCase
151 */ 150 */
152 public function testReset() 151 public function testReset()
153 { 152 {
154 $conf = $this->conf; 153 $confIO = $this->conf->getConfigIO();
155 $this->assertTrue($conf === ConfigManager::getInstance()); 154 $this->conf->reset();
156 $this->assertFalse($conf === $this->conf->reset()); 155 $this->assertFalse($confIO === $this->conf->getConfigIO());
157 $this->assertFalse($conf === ConfigManager::getInstance());
158 } 156 }
159 157
160 /** 158 /**
@@ -162,11 +160,11 @@ class ConfigManagerTest extends PHPUnit_Framework_TestCase
162 */ 160 */
163 public function testReload() 161 public function testReload()
164 { 162 {
165 ConfigManager::$CONFIG_FILE = 'tests/utils/config/configTmp'; 163 $this->conf->setConfigFile('tests/utils/config/configTmp');
166 $newConf = ConfigJson::getPhpHeaders() . '{ "key": "value" }'; 164 $newConf = ConfigJson::getPhpHeaders() . '{ "key": "value" }';
167 file_put_contents($this->conf->getConfigFile(), $newConf); 165 file_put_contents($this->conf->getConfigFileExt(), $newConf);
168 $this->conf->reload(); 166 $this->conf->reload();
169 unlink($this->conf->getConfigFile()); 167 unlink($this->conf->getConfigFileExt());
170 // Previous conf no longer exists, and new values have been loaded. 168 // Previous conf no longer exists, and new values have been loaded.
171 $this->assertFalse($this->conf->exists('credentials.login')); 169 $this->assertFalse($this->conf->exists('credentials.login'));
172 $this->assertEquals('value', $this->conf->get('key')); 170 $this->assertEquals('value', $this->conf->get('key'));