3 namespace Shaarli\Legacy
;
8 use ReflectionException
;
10 use Shaarli\Bookmark\Bookmark
;
11 use Shaarli\Bookmark\BookmarkArray
;
12 use Shaarli\Bookmark\BookmarkFilter
;
13 use Shaarli\Bookmark\BookmarkIO
;
14 use Shaarli\Bookmark\LinkDB
;
15 use Shaarli\Config\ConfigJson
;
16 use Shaarli\Config\ConfigManager
;
17 use Shaarli\Config\ConfigPhp
;
18 use Shaarli\Exceptions\IOException
;
19 use Shaarli\Helper\ApplicationUtils
;
20 use Shaarli\Thumbnailer
;
21 use Shaarli\Updater\Exception\UpdaterException
;
25 * Used to update stuff when a new Shaarli's version is reached.
26 * Update methods are ran only once, and the stored in a JSON file.
33 * @var array Updates which are already done.
35 protected $doneUpdates;
38 * @var LegacyLinkDB instance.
43 * @var ConfigManager $conf Configuration Manager instance.
48 * @var bool True if the user is logged in, false otherwise.
50 protected $isLoggedIn;
53 * @var array $_SESSION
58 * @var ReflectionMethod[] List of current class methods.
65 * @param array $doneUpdates Updates which are already done.
66 * @param LegacyLinkDB $linkDB LinkDB instance.
67 * @param ConfigManager $conf Configuration Manager instance.
68 * @param boolean $isLoggedIn True if the user is logged in.
69 * @param array $session $_SESSION (by reference)
71 * @throws ReflectionException
73 public function __construct($doneUpdates, $linkDB, $conf, $isLoggedIn, &$session = [])
75 $this->doneUpdates
= $doneUpdates;
76 $this->linkDB
= $linkDB;
78 $this->isLoggedIn
= $isLoggedIn;
79 $this->session
= &$session;
81 // Retrieve all update methods.
82 $class = new ReflectionClass($this);
83 $this->methods
= $class->getMethods();
87 * Run all new updates.
88 * Update methods have to start with 'updateMethod' and return true (on success).
90 * @return array An array containing ran updates.
92 * @throws UpdaterException If something went wrong.
94 public function update()
98 // If the user isn't logged in, exit without updating.
99 if ($this->isLoggedIn
!== true) {
103 if ($this->methods
=== null) {
104 throw new UpdaterException(t('Couldn\'t retrieve updater class methods.'));
107 foreach ($this->methods
as $method) {
108 // Not an update method or already done, pass.
110 !startsWith($method->getName(), 'updateMethod')
111 || in_array($method->getName(), $this->doneUpdates
)
117 $method->setAccessible(true);
118 $res = $method->invoke($this);
119 // Update method must return true to be considered processed.
121 $updatesRan[] = $method->getName();
123 } catch (Exception
$e) {
124 throw new UpdaterException($method, $e);
128 $this->doneUpdates
= array_merge($this->doneUpdates
, $updatesRan);
134 * @return array Updates methods already processed.
136 public function getDoneUpdates()
138 return $this->doneUpdates
;
142 * Move deprecated options.php to config.php.
144 * Milestone 0.9 (old versioning) - shaarli/Shaarli#41:
145 * options.php is not supported anymore.
147 public function updateMethodMergeDeprecatedConfigFile()
149 if (is_file($this->conf
->get('resource.data_dir') . '/options.php')) {
150 include $this->conf
->get('resource.data_dir') . '/options.php';
152 // Load GLOBALS into config
153 $allowedKeys = array_merge(ConfigPhp
::$ROOT_KEYS);
154 $allowedKeys[] = 'config';
155 foreach ($GLOBALS as $key => $value) {
156 if (in_array($key, $allowedKeys)) {
157 $this->conf
->set($key, $value);
160 $this->conf
->write($this->isLoggedIn
);
161 unlink($this->conf
->get('resource.data_dir') . '/options.php');
168 * Move old configuration in PHP to the new config system in JSON format.
170 * Will rename 'config.php' into 'config.save.php' and create 'config.json.php'.
171 * It will also convert legacy setting keys to the new ones.
173 public function updateMethodConfigToJson()
175 // JSON config already exists, nothing to do.
176 if ($this->conf
->getConfigIO() instanceof ConfigJson
) {
180 $configPhp = new ConfigPhp();
181 $configJson = new ConfigJson();
182 $oldConfig = $configPhp->read($this->conf
->getConfigFile() . '.php');
183 rename($this->conf
->getConfigFileExt(), $this->conf
->getConfigFile() . '.save.php');
184 $this->conf
->setConfigIO($configJson);
185 $this->conf
->reload();
187 $legacyMap = array_flip(ConfigPhp
::$LEGACY_KEYS_MAPPING);
188 foreach (ConfigPhp
::$ROOT_KEYS as $key) {
189 $this->conf
->set($legacyMap[$key], $oldConfig[$key]);
192 // Set sub config keys (config and plugins)
193 $subConfig = ['config', 'plugins'];
194 foreach ($subConfig as $sub) {
195 foreach ($oldConfig[$sub] as $key => $value) {
196 if (isset($legacyMap[$sub . '.' . $key])) {
197 $configKey = $legacyMap[$sub . '.' . $key];
199 $configKey = $sub . '.' . $key;
201 $this->conf
->set($configKey, $value);
206 $this->conf
->write($this->isLoggedIn
);
208 } catch (IOException
$e) {
209 error_log($e->getMessage());
215 * Escape settings which have been manually escaped in every request in previous versions:
217 * - general.header_link
220 * @return bool true if the update is successful, false otherwise.
222 public function updateMethodEscapeUnescapedConfig()
225 $this->conf
->set('general.title', escape($this->conf
->get('general.title')));
226 $this->conf
->set('general.header_link', escape($this->conf
->get('general.header_link')));
227 $this->conf
->write($this->isLoggedIn
);
228 } catch (Exception
$e) {
229 error_log($e->getMessage());
236 * Update the database to use the new ID system, which replaces linkdate primary keys.
237 * Also, creation and update dates are now DateTime objects (done by LinkDB).
239 * Since this update is very sensitve (changing the whole database), the datastore will be
240 * automatically backed up into the file datastore.<datetime>.php.
242 * LinkDB also adds the field 'shorturl' with the precedent format (linkdate smallhash),
243 * which will be saved by this method.
245 * @return bool true if the update is successful, false otherwise.
247 public function updateMethodDatastoreIds()
250 foreach ($this->linkDB
as $key => $link) {
255 // up to date database
256 if (is_int($first)) {
260 $save = $this->conf
->get('resource.data_dir') . '/datastore.' . date('YmdHis') . '.php';
261 copy($this->conf
->get('resource.datastore'), $save);
264 foreach ($this->linkDB
as $offset => $value) {
266 unset($this->linkDB
[$offset]);
268 $links = array_reverse($links);
270 foreach ($links as $l) {
271 unset($l['linkdate']);
273 $this->linkDB
[$cpt++
] = $l;
276 $this->linkDB
->save($this->conf
->get('resource.page_cache'));
277 $this->linkDB
->reorder();
283 * Rename tags starting with a '-' to work with tag exclusion search.
285 public function updateMethodRenameDashTags()
287 $linklist = $this->linkDB
->filterSearch();
288 foreach ($linklist as $key => $link) {
289 $link['tags'] = preg_replace('/(^| )\-/', '$1', $link['tags
']);
290 $link['tags
'] = implode(' ', array_unique(BookmarkFilter::tagsStrToArray($link['tags
'], true)));
291 $this->linkDB[$key] = $link;
293 $this->linkDB->save($this->conf->get('resource.page_cache
'));
298 * Initialize API settings:
299 * - api.enabled: true
300 * - api.secret: generated secret
302 public function updateMethodApiSettings()
304 if ($this->conf->exists('api
.secret
')) {
308 $this->conf->set('api
.enabled
', true);
312 $this->conf->get('credentials
.login
'),
313 $this->conf->get('credentials
.salt
')
316 $this->conf->write($this->isLoggedIn);
321 * New setting: theme name. If the default theme is used, nothing to do.
323 * If the user uses a custom theme, raintpl_tpl dir is updated to the parent directory,
324 * and the current theme is set as default in the theme setting.
326 * @return bool true if the update is successful, false otherwise.
328 public function updateMethodDefaultTheme()
330 // raintpl_tpl isn't the root template directory anymore
.
331 // We run the update only if this folder still contains the template files.
332 $tplDir = $this->conf
->get('resource.raintpl_tpl');
333 $tplFile = $tplDir . '/linklist.html';
334 if (!file_exists($tplFile)) {
338 $parent = dirname($tplDir);
339 $this->conf
->set('resource.raintpl_tpl', $parent);
340 $this->conf
->set('resource.theme', trim(str_replace($parent, '', $tplDir), '/'));
341 $this->conf
->write($this->isLoggedIn
);
343 // Dependency injection gore
344 RainTPL
::$tpl_dir = $tplDir;
350 * Move the file to inc/user.css to data/user.css.
352 * Note: Due to hardcoded paths, it's not unit testable. But one line of code should be fine.
354 * @return bool true if the update is successful, false otherwise.
356 public function updateMethodMoveUserCss()
358 if (!is_file('inc/user.css')) {
362 return rename('inc/user.css', 'data/user.css');
366 * * `markdown_escape` is a new setting, set to true as default.
368 * If the markdown plugin was already enabled, escaping is disabled to avoid
369 * breaking existing entries.
371 public function updateMethodEscapeMarkdown()
373 if ($this->conf
->exists('security.markdown_escape')) {
377 if (in_array('markdown', $this->conf
->get('general.enabled_plugins'))) {
378 $this->conf
->set('security.markdown_escape', false);
380 $this->conf
->set('security.markdown_escape', true);
382 $this->conf
->write($this->isLoggedIn
);
388 * Add 'http://' to Piwik URL the setting is set.
390 * @return bool true if the update is successful, false otherwise.
392 public function updateMethodPiwikUrl()
394 if (!$this->conf
->exists('plugins.PIWIK_URL') || startsWith($this->conf
->get('plugins.PIWIK_URL'), 'http')) {
398 $this->conf
->set('plugins.PIWIK_URL', 'http://' . $this->conf
->get('plugins.PIWIK_URL'));
399 $this->conf
->write($this->isLoggedIn
);
405 * Use ATOM feed as default.
407 public function updateMethodAtomDefault()
409 if (!$this->conf
->exists('feed.show_atom') || $this->conf
->get('feed.show_atom') === true) {
413 $this->conf
->set('feed.show_atom', true);
414 $this->conf
->write($this->isLoggedIn
);
420 * Update updates.check_updates_branch setting.
422 * If the current major version digit matches the latest branch
423 * major version digit, we set the branch to `latest`,
424 * otherwise we'll check updates on the `stable` branch.
426 * No update required for the dev version.
428 * Note: due to hardcoded URL and lack of dependency injection, this is not unit testable.
430 * FIXME! This needs to be removed when we switch to first digit major version
431 * instead of the second one since the versionning process will change.
433 public function updateMethodCheckUpdateRemoteBranch()
435 if (SHAARLI_VERSION
=== 'dev' || $this->conf
->get('updates.check_updates_branch') === 'latest') {
439 // Get latest branch major version digit
440 $latestVersion = ApplicationUtils
::getLatestGitVersionCode(
441 'https://raw.githubusercontent.com/shaarli/Shaarli/latest/shaarli_version.php',
444 if (preg_match('/(\d+)\.\d+$/', $latestVersion, $matches) === false) {
447 $latestMajor = $matches[1];
449 // Get current major version digit
450 preg_match('/(\d+)\.\d+$/', SHAARLI_VERSION
, $matches);
451 $currentMajor = $matches[1];
453 if ($currentMajor === $latestMajor) {
458 $this->conf
->set('updates.check_updates_branch', $branch);
459 $this->conf
->write($this->isLoggedIn
);
464 * Reset history store file due to date format change.
466 public function updateMethodResetHistoryFile()
468 if (is_file($this->conf
->get('resource.history'))) {
469 unlink($this->conf
->get('resource.history'));
475 * Save the datastore -> the link order is now applied when bookmarks are saved.
477 public function updateMethodReorderDatastore()
479 $this->linkDB
->save($this->conf
->get('resource.page_cache'));
484 * Change privateonly session key to visibility.
486 public function updateMethodVisibilitySession()
488 if (isset($_SESSION['privateonly'])) {
489 unset($_SESSION['privateonly']);
490 $_SESSION['visibility'] = 'private';
496 * Add download size and timeout to the configuration file
498 * @return bool true if the update is successful, false otherwise.
500 public function updateMethodDownloadSizeAndTimeoutConf()
503 $this->conf
->exists('general.download_max_size')
504 && $this->conf
->exists('general.download_timeout')
509 if (!$this->conf
->exists('general.download_max_size')) {
510 $this->conf
->set('general.download_max_size', 1024 * 1024 * 4);
513 if (!$this->conf
->exists('general.download_timeout')) {
514 $this->conf
->set('general.download_timeout', 30);
517 $this->conf
->write($this->isLoggedIn
);
522 * * Move thumbnails management to WebThumbnailer, coming with new settings.
524 public function updateMethodWebThumbnailer()
526 if ($this->conf
->exists('thumbnails.mode')) {
530 $thumbnailsEnabled = extension_loaded('gd') && $this->conf
->get('thumbnail.enable_thumbnails', true);
531 $this->conf
->set('thumbnails.mode', $thumbnailsEnabled ? Thumbnailer
::MODE_ALL
: Thumbnailer
::MODE_NONE
);
532 $this->conf
->set('thumbnails.width', 125);
533 $this->conf
->set('thumbnails.height', 90);
534 $this->conf
->remove('thumbnail');
535 $this->conf
->write(true);
537 if ($thumbnailsEnabled) {
538 $this->session
['warnings'][] = t(
539 t('You have enabled or changed thumbnails mode.') .
540 '<a href="./admin/thumbnails">' . t('Please synchronize them.') . '</a>'
548 * Set sticky = false on all bookmarks
550 * @return bool true if the update is successful, false otherwise.
552 public function updateMethodSetSticky()
554 foreach ($this->linkDB
as $key => $link) {
555 if (isset($link['sticky'])) {
558 $link['sticky'] = false;
559 $this->linkDB
[$key] = $link;
562 $this->linkDB
->save($this->conf
->get('resource.page_cache'));
568 * Remove redirector settings.
570 public function updateMethodRemoveRedirector()
572 $this->conf
->remove('redirector');
573 $this->conf
->write(true);
578 * Migrate the legacy arrays to Bookmark objects.
579 * Also make a backup of the datastore.
581 public function updateMethodMigrateDatabase()
583 $save = $this->conf
->get('resource.data_dir') . '/datastore.' . date('YmdHis') . '_1.php';
584 if (! copy($this->conf
->get('resource.datastore'), $save)) {
585 die('Could not backup the datastore.');
588 $linksArray = new BookmarkArray();
589 foreach ($this->linkDB
as $key => $link) {
590 $linksArray[$key] = (new Bookmark())->fromArray($link, $this->conf
->get('general.tags_separator', ' '));
592 $linksIo = new BookmarkIO($this->conf
);
593 $linksIo->write($linksArray);
599 * Write the `formatter` setting in config file.
600 * Use markdown if the markdown plugin is enabled, the default one otherwise.
601 * Also remove markdown plugin setting as it is now integrated to the core.
603 public function updateMethodFormatterSetting()
605 if (!$this->conf
->exists('formatter') || $this->conf
->get('formatter') === 'default') {
606 $enabledPlugins = $this->conf
->get('general.enabled_plugins');
607 if (($pos = array_search('markdown', $enabledPlugins)) !== false) {
608 $formatter = 'markdown';
609 unset($enabledPlugins[$pos]);
610 $this->conf
->set('general.enabled_plugins', array_values($enabledPlugins));
612 $formatter = 'default';
614 $this->conf
->set('formatter', $formatter);
615 $this->conf
->write(true);