2 use Shaarli\Config\ConfigJson
;
3 use Shaarli\Config\ConfigPhp
;
4 use Shaarli\Config\ConfigManager
;
5 use Shaarli\Exceptions\IOException
;
6 use Shaarli\Thumbnailer
;
10 * Used to update stuff when a new Shaarli's version is reached.
11 * Update methods are ran only once, and the stored in a JSON file.
16 * @var array Updates which are already done.
18 protected $doneUpdates;
21 * @var LinkDB instance.
26 * @var ConfigManager $conf Configuration Manager instance.
31 * @var bool True if the user is logged in, false otherwise.
33 protected $isLoggedIn;
36 * @var array $_SESSION
41 * @var ReflectionMethod[] List of current class methods.
48 * @param array $doneUpdates Updates which are already done.
49 * @param LinkDB $linkDB LinkDB instance.
50 * @param ConfigManager $conf Configuration Manager instance.
51 * @param boolean $isLoggedIn True if the user is logged in.
52 * @param array $session $_SESSION (by reference)
54 * @throws ReflectionException
56 public function __construct($doneUpdates, $linkDB, $conf, $isLoggedIn, &$session = [])
58 $this->doneUpdates
= $doneUpdates;
59 $this->linkDB
= $linkDB;
61 $this->isLoggedIn
= $isLoggedIn;
62 $this->session
= &$session;
64 // Retrieve all update methods.
65 $class = new ReflectionClass($this);
66 $this->methods
= $class->getMethods();
70 * Run all new updates.
71 * Update methods have to start with 'updateMethod' and return true (on success).
73 * @return array An array containing ran updates.
75 * @throws UpdaterException If something went wrong.
77 public function update()
79 $updatesRan = array();
81 // If the user isn't logged in, exit without updating.
82 if ($this->isLoggedIn
!== true) {
86 if ($this->methods
=== null) {
87 throw new UpdaterException(t('Couldn\'t retrieve Updater class methods.'));
90 foreach ($this->methods
as $method) {
91 // Not an update method or already done, pass.
92 if (! startsWith($method->getName(), 'updateMethod')
93 || in_array($method->getName(), $this->doneUpdates
)
99 $method->setAccessible(true);
100 $res = $method->invoke($this);
101 // Update method must return true to be considered processed.
103 $updatesRan[] = $method->getName();
105 } catch (Exception
$e) {
106 throw new UpdaterException($method, $e);
110 $this->doneUpdates
= array_merge($this->doneUpdates
, $updatesRan);
116 * @return array Updates methods already processed.
118 public function getDoneUpdates()
120 return $this->doneUpdates
;
124 * Move deprecated options.php to config.php.
126 * Milestone 0.9 (old versioning) - shaarli/Shaarli#41:
127 * options.php is not supported anymore.
129 public function updateMethodMergeDeprecatedConfigFile()
131 if (is_file($this->conf
->get('resource.data_dir') . '/options.php')) {
132 include $this->conf
->get('resource.data_dir') . '/options.php';
134 // Load GLOBALS into config
135 $allowedKeys = array_merge(ConfigPhp
::$ROOT_KEYS);
136 $allowedKeys[] = 'config';
137 foreach ($GLOBALS as $key => $value) {
138 if (in_array($key, $allowedKeys)) {
139 $this->conf
->set($key, $value);
142 $this->conf
->write($this->isLoggedIn
);
143 unlink($this->conf
->get('resource.data_dir').'/options.php');
150 * Move old configuration in PHP to the new config system in JSON format.
152 * Will rename 'config.php' into 'config.save.php' and create 'config.json.php'.
153 * It will also convert legacy setting keys to the new ones.
155 public function updateMethodConfigToJson()
157 // JSON config already exists, nothing to do.
158 if ($this->conf
->getConfigIO() instanceof ConfigJson
) {
162 $configPhp = new ConfigPhp();
163 $configJson = new ConfigJson();
164 $oldConfig = $configPhp->read($this->conf
->getConfigFile() . '.php');
165 rename($this->conf
->getConfigFileExt(), $this->conf
->getConfigFile() . '.save.php');
166 $this->conf
->setConfigIO($configJson);
167 $this->conf
->reload();
169 $legacyMap = array_flip(ConfigPhp
::$LEGACY_KEYS_MAPPING);
170 foreach (ConfigPhp
::$ROOT_KEYS as $key) {
171 $this->conf
->set($legacyMap[$key], $oldConfig[$key]);
174 // Set sub config keys (config and plugins)
175 $subConfig = array('config', 'plugins');
176 foreach ($subConfig as $sub) {
177 foreach ($oldConfig[$sub] as $key => $value) {
178 if (isset($legacyMap[$sub .'.'. $key])) {
179 $configKey = $legacyMap[$sub .'.'. $key];
181 $configKey = $sub .'.'. $key;
183 $this->conf
->set($configKey, $value);
188 $this->conf
->write($this->isLoggedIn
);
190 } catch (IOException
$e) {
191 error_log($e->getMessage());
197 * Escape settings which have been manually escaped in every request in previous versions:
199 * - general.header_link
202 * @return bool true if the update is successful, false otherwise.
204 public function updateMethodEscapeUnescapedConfig()
207 $this->conf
->set('general.title', escape($this->conf
->get('general.title')));
208 $this->conf
->set('general.header_link', escape($this->conf
->get('general.header_link')));
209 $this->conf
->set('redirector.url', escape($this->conf
->get('redirector.url')));
210 $this->conf
->write($this->isLoggedIn
);
211 } catch (Exception
$e) {
212 error_log($e->getMessage());
219 * Update the database to use the new ID system, which replaces linkdate primary keys.
220 * Also, creation and update dates are now DateTime objects (done by LinkDB).
222 * Since this update is very sensitve (changing the whole database), the datastore will be
223 * automatically backed up into the file datastore.<datetime>.php.
225 * LinkDB also adds the field 'shorturl' with the precedent format (linkdate smallhash),
226 * which will be saved by this method.
228 * @return bool true if the update is successful, false otherwise.
230 public function updateMethodDatastoreIds()
232 // up to date database
233 if (isset($this->linkDB
[0])) {
237 $save = $this->conf
->get('resource.data_dir') .'/datastore.'. date('YmdHis') .'.php';
238 copy($this->conf
->get('resource.datastore'), $save);
241 foreach ($this->linkDB
as $offset => $value) {
243 unset($this->linkDB
[$offset]);
245 $links = array_reverse($links);
247 foreach ($links as $l) {
248 unset($l['linkdate']);
250 $this->linkDB
[$cpt++
] = $l;
253 $this->linkDB
->save($this->conf
->get('resource.page_cache'));
254 $this->linkDB
->reorder();
260 * Rename tags starting with a '-' to work with tag exclusion search.
262 public function updateMethodRenameDashTags()
264 $linklist = $this->linkDB
->filterSearch();
265 foreach ($linklist as $key => $link) {
266 $link['tags'] = preg_replace('/(^| )\-/', '$1', $link['tags
']);
267 $link['tags
'] = implode(' ', array_unique(LinkFilter::tagsStrToArray($link['tags
'], true)));
268 $this->linkDB[$key] = $link;
270 $this->linkDB->save($this->conf->get('resource.page_cache
'));
275 * Initialize API settings:
276 * - api.enabled: true
277 * - api.secret: generated secret
279 public function updateMethodApiSettings()
281 if ($this->conf->exists('api
.secret
')) {
285 $this->conf->set('api
.enabled
', true);
289 $this->conf->get('credentials
.login
'),
290 $this->conf->get('credentials
.salt
')
293 $this->conf->write($this->isLoggedIn);
298 * New setting: theme name. If the default theme is used, nothing to do.
300 * If the user uses a custom theme, raintpl_tpl dir is updated to the parent directory,
301 * and the current theme is set as default in the theme setting.
303 * @return bool true if the update is successful, false otherwise.
305 public function updateMethodDefaultTheme()
307 // raintpl_tpl isn't the root template directory anymore
.
308 // We run the update only if this folder still contains the template files.
309 $tplDir = $this->conf
->get('resource.raintpl_tpl');
310 $tplFile = $tplDir . '/linklist.html';
311 if (! file_exists($tplFile)) {
315 $parent = dirname($tplDir);
316 $this->conf
->set('resource.raintpl_tpl', $parent);
317 $this->conf
->set('resource.theme', trim(str_replace($parent, '', $tplDir), '/'));
318 $this->conf
->write($this->isLoggedIn
);
320 // Dependency injection gore
321 RainTPL
::$tpl_dir = $tplDir;
327 * Move the file to inc/user.css to data/user.css.
329 * Note: Due to hardcoded paths, it's not unit testable. But one line of code should be fine.
331 * @return bool true if the update is successful, false otherwise.
333 public function updateMethodMoveUserCss()
335 if (! is_file('inc/user.css')) {
339 return rename('inc/user.css', 'data/user.css');
343 * * `markdown_escape` is a new setting, set to true as default.
345 * If the markdown plugin was already enabled, escaping is disabled to avoid
346 * breaking existing entries.
348 public function updateMethodEscapeMarkdown()
350 if ($this->conf
->exists('security.markdown_escape')) {
354 if (in_array('markdown', $this->conf
->get('general.enabled_plugins'))) {
355 $this->conf
->set('security.markdown_escape', false);
357 $this->conf
->set('security.markdown_escape', true);
359 $this->conf
->write($this->isLoggedIn
);
365 * Add 'http://' to Piwik URL the setting is set.
367 * @return bool true if the update is successful, false otherwise.
369 public function updateMethodPiwikUrl()
371 if (! $this->conf
->exists('plugins.PIWIK_URL') || startsWith($this->conf
->get('plugins.PIWIK_URL'), 'http')) {
375 $this->conf
->set('plugins.PIWIK_URL', 'http://'. $this->conf
->get('plugins.PIWIK_URL'));
376 $this->conf
->write($this->isLoggedIn
);
382 * Use ATOM feed as default.
384 public function updateMethodAtomDefault()
386 if (!$this->conf
->exists('feed.show_atom') || $this->conf
->get('feed.show_atom') === true) {
390 $this->conf
->set('feed.show_atom', true);
391 $this->conf
->write($this->isLoggedIn
);
397 * Update updates.check_updates_branch setting.
399 * If the current major version digit matches the latest branch
400 * major version digit, we set the branch to `latest`,
401 * otherwise we'll check updates on the `stable` branch.
403 * No update required for the dev version.
405 * Note: due to hardcoded URL and lack of dependency injection, this is not unit testable.
407 * FIXME! This needs to be removed when we switch to first digit major version
408 * instead of the second one since the versionning process will change.
410 public function updateMethodCheckUpdateRemoteBranch()
412 if (SHAARLI_VERSION
=== 'dev' || $this->conf
->get('updates.check_updates_branch') === 'latest') {
416 // Get latest branch major version digit
417 $latestVersion = ApplicationUtils
::getLatestGitVersionCode(
418 'https://raw.githubusercontent.com/shaarli/Shaarli/latest/shaarli_version.php',
421 if (preg_match('/(\d+)\.\d+$/', $latestVersion, $matches) === false) {
424 $latestMajor = $matches[1];
426 // Get current major version digit
427 preg_match('/(\d+)\.\d+$/', SHAARLI_VERSION
, $matches);
428 $currentMajor = $matches[1];
430 if ($currentMajor === $latestMajor) {
435 $this->conf
->set('updates.check_updates_branch', $branch);
436 $this->conf
->write($this->isLoggedIn
);
441 * Reset history store file due to date format change.
443 public function updateMethodResetHistoryFile()
445 if (is_file($this->conf
->get('resource.history'))) {
446 unlink($this->conf
->get('resource.history'));
452 * Save the datastore -> the link order is now applied when links are saved.
454 public function updateMethodReorderDatastore()
456 $this->linkDB
->save($this->conf
->get('resource.page_cache'));
461 * Change privateonly session key to visibility.
463 public function updateMethodVisibilitySession()
465 if (isset($_SESSION['privateonly'])) {
466 unset($_SESSION['privateonly']);
467 $_SESSION['visibility'] = 'private';
473 * Add download size and timeout to the configuration file
475 * @return bool true if the update is successful, false otherwise.
477 public function updateMethodDownloadSizeAndTimeoutConf()
479 if ($this->conf
->exists('general.download_max_size')
480 && $this->conf
->exists('general.download_timeout')
485 if (! $this->conf
->exists('general.download_max_size')) {
486 $this->conf
->set('general.download_max_size', 1024*1024*4);
489 if (! $this->conf
->exists('general.download_timeout')) {
490 $this->conf
->set('general.download_timeout', 30);
493 $this->conf
->write($this->isLoggedIn
);
498 * * Move thumbnails management to WebThumbnailer, coming with new settings.
500 public function updateMethodWebThumbnailer()
502 if ($this->conf
->exists('thumbnails.mode')) {
506 $thumbnailsEnabled = extension_loaded('gd') && $this->conf
->get('thumbnail.enable_thumbnails', true);
507 $this->conf
->set('thumbnails.mode', $thumbnailsEnabled ? Thumbnailer
::MODE_ALL
: Thumbnailer
::MODE_NONE
);
508 $this->conf
->set('thumbnails.width', 125);
509 $this->conf
->set('thumbnails.height', 90);
510 $this->conf
->remove('thumbnail');
511 $this->conf
->write(true);
513 if ($thumbnailsEnabled) {
514 $this->session
['warnings'][] = t(
515 'You have enabled or changed thumbnails mode. <a href="?do=thumbs_update">Please synchronize them</a>.'
523 * Set sticky = false on all links
525 * @return bool true if the update is successful, false otherwise.
527 public function updateMethodSetSticky()
529 foreach ($this->linkDB
as $key => $link) {
530 if (isset($link['sticky'])) {
533 $link['sticky'] = false;
534 $this->linkDB
[$key] = $link;
537 $this->linkDB
->save($this->conf
->get('resource.page_cache'));
544 * Class UpdaterException.
546 class UpdaterException
extends Exception
549 * @var string Method where the error occurred.
554 * @var Exception The parent exception.
561 * @param string $message Force the error message if set.
562 * @param string $method Method where the error occurred.
563 * @param Exception|bool $previous Parent exception.
565 public function __construct($message = '', $method = '', $previous = false)
567 $this->method
= $method;
568 $this->previous
= $previous;
569 $this->message
= $this->buildMessage($message);
573 * Build the exception error message.
575 * @param string $message Optional given error message.
577 * @return string The built error message.
579 private function buildMessage($message)
582 if (! empty($message)) {
583 $out .= $message . PHP_EOL
;
586 if (! empty($this->method
)) {
587 $out .= t('An error occurred while running the update ') . $this->method
. PHP_EOL
;
590 if (! empty($this->previous
)) {
591 $out .= ' '. $this->previous
->getMessage();
599 * Read the updates file, and return already done updates.
601 * @param string $updatesFilepath Updates file path.
603 * @return array Already done update methods.
605 function read_updates_file($updatesFilepath)
607 if (! empty($updatesFilepath) && is_file($updatesFilepath)) {
608 $content = file_get_contents($updatesFilepath);
609 if (! empty($content)) {
610 return explode(';', $content);
617 * Write updates file.
619 * @param string $updatesFilepath Updates file path.
620 * @param array $updates Updates array to write.
622 * @throws Exception Couldn't write version number.
624 function write_updates_file($updatesFilepath, $updates)
626 if (empty($updatesFilepath)) {
627 throw new Exception(t('Updates file path is not set, can\'t write updates.'));
630 $res = file_put_contents($updatesFilepath, implode(';', $updates));
631 if ($res === false) {
632 throw new Exception(t('Unable to write updates in '. $updatesFilepath . '.'));