2 use Shaarli\Config\ConfigJson
;
3 use Shaarli\Config\ConfigPhp
;
7 * Used to update stuff when a new Shaarli's version is reached.
8 * Update methods are ran only once, and the stored in a JSON file.
13 * @var array Updates which are already done.
15 protected $doneUpdates;
18 * @var LinkDB instance.
23 * @var ConfigManager $conf Configuration Manager instance.
28 * @var bool True if the user is logged in, false otherwise.
30 protected $isLoggedIn;
33 * @var ReflectionMethod[] List of current class methods.
40 * @param array $doneUpdates Updates which are already done.
41 * @param LinkDB $linkDB LinkDB instance.
42 * @param ConfigManager $conf Configuration Manager instance.
43 * @param boolean $isLoggedIn True if the user is logged in.
45 public function __construct($doneUpdates, $linkDB, $conf, $isLoggedIn)
47 $this->doneUpdates
= $doneUpdates;
48 $this->linkDB
= $linkDB;
50 $this->isLoggedIn
= $isLoggedIn;
52 // Retrieve all update methods.
53 $class = new ReflectionClass($this);
54 $this->methods
= $class->getMethods();
58 * Run all new updates.
59 * Update methods have to start with 'updateMethod' and return true (on success).
61 * @return array An array containing ran updates.
63 * @throws UpdaterException If something went wrong.
65 public function update()
67 $updatesRan = array();
69 // If the user isn't logged in, exit without updating.
70 if ($this->isLoggedIn
!== true) {
74 if ($this->methods
=== null) {
75 throw new UpdaterException('Couldn\'t retrieve Updater class methods.');
78 foreach ($this->methods
as $method) {
79 // Not an update method or already done, pass.
80 if (! startsWith($method->getName(), 'updateMethod')
81 || in_array($method->getName(), $this->doneUpdates
)
87 $method->setAccessible(true);
88 $res = $method->invoke($this);
89 // Update method must return true to be considered processed.
91 $updatesRan[] = $method->getName();
93 } catch (Exception
$e) {
94 throw new UpdaterException($method, $e);
98 $this->doneUpdates
= array_merge($this->doneUpdates
, $updatesRan);
104 * @return array Updates methods already processed.
106 public function getDoneUpdates()
108 return $this->doneUpdates
;
112 * Move deprecated options.php to config.php.
114 * Milestone 0.9 (old versioning) - shaarli/Shaarli#41:
115 * options.php is not supported anymore.
117 public function updateMethodMergeDeprecatedConfigFile()
119 if (is_file($this->conf
->get('resource.data_dir') . '/options.php')) {
120 include $this->conf
->get('resource.data_dir') . '/options.php';
122 // Load GLOBALS into config
123 $allowedKeys = array_merge(ConfigPhp
::$ROOT_KEYS);
124 $allowedKeys[] = 'config';
125 foreach ($GLOBALS as $key => $value) {
126 if (in_array($key, $allowedKeys)) {
127 $this->conf
->set($key, $value);
130 $this->conf
->write($this->isLoggedIn
);
131 unlink($this->conf
->get('resource.data_dir').'/options.php');
138 * Move old configuration in PHP to the new config system in JSON format.
140 * Will rename 'config.php' into 'config.save.php' and create 'config.json.php'.
141 * It will also convert legacy setting keys to the new ones.
143 public function updateMethodConfigToJson()
145 // JSON config already exists, nothing to do.
146 if ($this->conf
->getConfigIO() instanceof ConfigJson
) {
150 $configPhp = new ConfigPhp();
151 $configJson = new ConfigJson();
152 $oldConfig = $configPhp->read($this->conf
->getConfigFile() . '.php');
153 rename($this->conf
->getConfigFileExt(), $this->conf
->getConfigFile() . '.save.php');
154 $this->conf
->setConfigIO($configJson);
155 $this->conf
->reload();
157 $legacyMap = array_flip(ConfigPhp
::$LEGACY_KEYS_MAPPING);
158 foreach (ConfigPhp
::$ROOT_KEYS as $key) {
159 $this->conf
->set($legacyMap[$key], $oldConfig[$key]);
162 // Set sub config keys (config and plugins)
163 $subConfig = array('config', 'plugins');
164 foreach ($subConfig as $sub) {
165 foreach ($oldConfig[$sub] as $key => $value) {
166 if (isset($legacyMap[$sub .'.'. $key])) {
167 $configKey = $legacyMap[$sub .'.'. $key];
169 $configKey = $sub .'.'. $key;
171 $this->conf
->set($configKey, $value);
176 $this->conf
->write($this->isLoggedIn
);
178 } catch (IOException
$e) {
179 error_log($e->getMessage());
185 * Escape settings which have been manually escaped in every request in previous versions:
187 * - general.header_link
190 * @return bool true if the update is successful, false otherwise.
192 public function updateMethodEscapeUnescapedConfig()
195 $this->conf
->set('general.title', escape($this->conf
->get('general.title')));
196 $this->conf
->set('general.header_link', escape($this->conf
->get('general.header_link')));
197 $this->conf
->set('redirector.url', escape($this->conf
->get('redirector.url')));
198 $this->conf
->write($this->isLoggedIn
);
199 } catch (Exception
$e) {
200 error_log($e->getMessage());
207 * Update the database to use the new ID system, which replaces linkdate primary keys.
208 * Also, creation and update dates are now DateTime objects (done by LinkDB).
210 * Since this update is very sensitve (changing the whole database), the datastore will be
211 * automatically backed up into the file datastore.<datetime>.php.
213 * LinkDB also adds the field 'shorturl' with the precedent format (linkdate smallhash),
214 * which will be saved by this method.
216 * @return bool true if the update is successful, false otherwise.
218 public function updateMethodDatastoreIds()
220 // up to date database
221 if (isset($this->linkDB
[0])) {
225 $save = $this->conf
->get('resource.data_dir') .'/datastore.'. date('YmdHis') .'.php';
226 copy($this->conf
->get('resource.datastore'), $save);
229 foreach ($this->linkDB
as $offset => $value) {
231 unset($this->linkDB
[$offset]);
233 $links = array_reverse($links);
235 foreach ($links as $l) {
236 unset($l['linkdate']);
238 $this->linkDB
[$cpt++
] = $l;
241 $this->linkDB
->save($this->conf
->get('resource.page_cache'));
242 $this->linkDB
->reorder();
248 * Rename tags starting with a '-' to work with tag exclusion search.
250 public function updateMethodRenameDashTags()
252 $linklist = $this->linkDB
->filterSearch();
253 foreach ($linklist as $key => $link) {
254 $link['tags'] = preg_replace('/(^| )\-/', '$1', $link['tags
']);
255 $link['tags
'] = implode(' ', array_unique(LinkFilter::tagsStrToArray($link['tags
'], true)));
256 $this->linkDB[$key] = $link;
258 $this->linkDB->save($this->conf->get('resource.page_cache
'));
263 * Initialize API settings:
264 * - api.enabled: true
265 * - api.secret: generated secret
267 public function updateMethodApiSettings()
269 if ($this->conf->exists('api
.secret
')) {
273 $this->conf->set('api
.enabled
', true);
277 $this->conf->get('credentials
.login
'),
278 $this->conf->get('credentials
.salt
')
281 $this->conf->write($this->isLoggedIn);
286 * New setting: theme name. If the default theme is used, nothing to do.
288 * If the user uses a custom theme, raintpl_tpl dir is updated to the parent directory,
289 * and the current theme is set as default in the theme setting.
291 * @return bool true if the update is successful, false otherwise.
293 public function updateMethodDefaultTheme()
295 // raintpl_tpl isn't the root template directory anymore
.
296 // We run the update only if this folder still contains the template files.
297 $tplDir = $this->conf
->get('resource.raintpl_tpl');
298 $tplFile = $tplDir . '/linklist.html';
299 if (! file_exists($tplFile)) {
303 $parent = dirname($tplDir);
304 $this->conf
->set('resource.raintpl_tpl', $parent);
305 $this->conf
->set('resource.theme', trim(str_replace($parent, '', $tplDir), '/'));
306 $this->conf
->write($this->isLoggedIn
);
308 // Dependency injection gore
309 RainTPL
::$tpl_dir = $tplDir;
315 * Move the file to inc/user.css to data/user.css.
317 * Note: Due to hardcoded paths, it's not unit testable. But one line of code should be fine.
319 * @return bool true if the update is successful, false otherwise.
321 public function updateMethodMoveUserCss()
323 if (! is_file('inc/user.css')) {
327 return rename('inc/user.css', 'data/user.css');
331 * While the new default theme is in an unstable state
332 * continue to use the vintage theme
334 public function updateMethodDefaultThemeVintage()
336 if ($this->conf
->get('resource.theme') !== 'default') {
339 $this->conf
->set('resource.theme', 'vintage');
340 $this->conf
->write($this->isLoggedIn
);
346 * * `markdown_escape` is a new setting, set to true as default.
348 * If the markdown plugin was already enabled, escaping is disabled to avoid
349 * breaking existing entries.
351 public function updateMethodEscapeMarkdown()
353 if ($this->conf
->exists('security.markdown_escape')) {
357 if (in_array('markdown', $this->conf
->get('general.enabled_plugins'))) {
358 $this->conf
->set('security.markdown_escape', false);
360 $this->conf
->set('security.markdown_escape', true);
362 $this->conf
->write($this->isLoggedIn
);
369 * Class UpdaterException.
371 class UpdaterException
extends Exception
374 * @var string Method where the error occurred.
379 * @var Exception The parent exception.
386 * @param string $message Force the error message if set.
387 * @param string $method Method where the error occurred.
388 * @param Exception|bool $previous Parent exception.
390 public function __construct($message = '', $method = '', $previous = false)
392 $this->method
= $method;
393 $this->previous
= $previous;
394 $this->message
= $this->buildMessage($message);
398 * Build the exception error message.
400 * @param string $message Optional given error message.
402 * @return string The built error message.
404 private function buildMessage($message)
407 if (! empty($message)) {
408 $out .= $message . PHP_EOL
;
411 if (! empty($this->method
)) {
412 $out .= 'An error occurred while running the update '. $this->method
. PHP_EOL
;
415 if (! empty($this->previous
)) {
416 $out .= ' '. $this->previous
->getMessage();
424 * Read the updates file, and return already done updates.
426 * @param string $updatesFilepath Updates file path.
428 * @return array Already done update methods.
430 function read_updates_file($updatesFilepath)
432 if (! empty($updatesFilepath) && is_file($updatesFilepath)) {
433 $content = file_get_contents($updatesFilepath);
434 if (! empty($content)) {
435 return explode(';', $content);
442 * Write updates file.
444 * @param string $updatesFilepath Updates file path.
445 * @param array $updates Updates array to write.
447 * @throws Exception Couldn't write version number.
449 function write_updates_file($updatesFilepath, $updates)
451 if (empty($updatesFilepath)) {
452 throw new Exception('Updates file path is not set, can\'t write updates.');
455 $res = file_put_contents($updatesFilepath, implode(';', $updates));
456 if ($res === false) {
457 throw new Exception('Unable to write updates in '. $updatesFilepath . '.');