3 namespace Shaarli\Legacy
;
8 use ReflectionException
;
10 use Shaarli\ApplicationUtils
;
11 use Shaarli\Bookmark\Bookmark
;
12 use Shaarli\Bookmark\BookmarkArray
;
13 use Shaarli\Bookmark\BookmarkFilter
;
14 use Shaarli\Bookmark\BookmarkIO
;
15 use Shaarli\Bookmark\LinkDB
;
16 use Shaarli\Config\ConfigJson
;
17 use Shaarli\Config\ConfigManager
;
18 use Shaarli\Config\ConfigPhp
;
19 use Shaarli\Exceptions\IOException
;
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()
96 $updatesRan = array();
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.
109 if (!startsWith($method->getName(), 'updateMethod')
110 || in_array($method->getName(), $this->doneUpdates
)
116 $method->setAccessible(true);
117 $res = $method->invoke($this);
118 // Update method must return true to be considered processed.
120 $updatesRan[] = $method->getName();
122 } catch (Exception
$e) {
123 throw new UpdaterException($method, $e);
127 $this->doneUpdates
= array_merge($this->doneUpdates
, $updatesRan);
133 * @return array Updates methods already processed.
135 public function getDoneUpdates()
137 return $this->doneUpdates
;
141 * Move deprecated options.php to config.php.
143 * Milestone 0.9 (old versioning) - shaarli/Shaarli#41:
144 * options.php is not supported anymore.
146 public function updateMethodMergeDeprecatedConfigFile()
148 if (is_file($this->conf
->get('resource.data_dir') . '/options.php')) {
149 include $this->conf
->get('resource.data_dir') . '/options.php';
151 // Load GLOBALS into config
152 $allowedKeys = array_merge(ConfigPhp
::$ROOT_KEYS);
153 $allowedKeys[] = 'config';
154 foreach ($GLOBALS as $key => $value) {
155 if (in_array($key, $allowedKeys)) {
156 $this->conf
->set($key, $value);
159 $this->conf
->write($this->isLoggedIn
);
160 unlink($this->conf
->get('resource.data_dir') . '/options.php');
167 * Move old configuration in PHP to the new config system in JSON format.
169 * Will rename 'config.php' into 'config.save.php' and create 'config.json.php'.
170 * It will also convert legacy setting keys to the new ones.
172 public function updateMethodConfigToJson()
174 // JSON config already exists, nothing to do.
175 if ($this->conf
->getConfigIO() instanceof ConfigJson
) {
179 $configPhp = new ConfigPhp();
180 $configJson = new ConfigJson();
181 $oldConfig = $configPhp->read($this->conf
->getConfigFile() . '.php');
182 rename($this->conf
->getConfigFileExt(), $this->conf
->getConfigFile() . '.save.php');
183 $this->conf
->setConfigIO($configJson);
184 $this->conf
->reload();
186 $legacyMap = array_flip(ConfigPhp
::$LEGACY_KEYS_MAPPING);
187 foreach (ConfigPhp
::$ROOT_KEYS as $key) {
188 $this->conf
->set($legacyMap[$key], $oldConfig[$key]);
191 // Set sub config keys (config and plugins)
192 $subConfig = array('config', 'plugins');
193 foreach ($subConfig as $sub) {
194 foreach ($oldConfig[$sub] as $key => $value) {
195 if (isset($legacyMap[$sub . '.' . $key])) {
196 $configKey = $legacyMap[$sub . '.' . $key];
198 $configKey = $sub . '.' . $key;
200 $this->conf
->set($configKey, $value);
205 $this->conf
->write($this->isLoggedIn
);
207 } catch (IOException
$e) {
208 error_log($e->getMessage());
214 * Escape settings which have been manually escaped in every request in previous versions:
216 * - general.header_link
219 * @return bool true if the update is successful, false otherwise.
221 public function updateMethodEscapeUnescapedConfig()
224 $this->conf
->set('general.title', escape($this->conf
->get('general.title')));
225 $this->conf
->set('general.header_link', escape($this->conf
->get('general.header_link')));
226 $this->conf
->write($this->isLoggedIn
);
227 } catch (Exception
$e) {
228 error_log($e->getMessage());
235 * Update the database to use the new ID system, which replaces linkdate primary keys.
236 * Also, creation and update dates are now DateTime objects (done by LinkDB).
238 * Since this update is very sensitve (changing the whole database), the datastore will be
239 * automatically backed up into the file datastore.<datetime>.php.
241 * LinkDB also adds the field 'shorturl' with the precedent format (linkdate smallhash),
242 * which will be saved by this method.
244 * @return bool true if the update is successful, false otherwise.
246 public function updateMethodDatastoreIds()
249 foreach ($this->linkDB
as $key => $link) {
254 // up to date database
255 if (is_int($first)) {
259 $save = $this->conf
->get('resource.data_dir') . '/datastore.' . date('YmdHis') . '.php';
260 copy($this->conf
->get('resource.datastore'), $save);
263 foreach ($this->linkDB
as $offset => $value) {
265 unset($this->linkDB
[$offset]);
267 $links = array_reverse($links);
269 foreach ($links as $l) {
270 unset($l['linkdate']);
272 $this->linkDB
[$cpt++
] = $l;
275 $this->linkDB
->save($this->conf
->get('resource.page_cache'));
276 $this->linkDB
->reorder();
282 * Rename tags starting with a '-' to work with tag exclusion search.
284 public function updateMethodRenameDashTags()
286 $linklist = $this->linkDB
->filterSearch();
287 foreach ($linklist as $key => $link) {
288 $link['tags'] = preg_replace('/(^| )\-/', '$1', $link['tags
']);
289 $link['tags
'] = implode(' ', array_unique(BookmarkFilter::tagsStrToArray($link['tags
'], true)));
290 $this->linkDB[$key] = $link;
292 $this->linkDB->save($this->conf->get('resource.page_cache
'));
297 * Initialize API settings:
298 * - api.enabled: true
299 * - api.secret: generated secret
301 public function updateMethodApiSettings()
303 if ($this->conf->exists('api
.secret
')) {
307 $this->conf->set('api
.enabled
', true);
311 $this->conf->get('credentials
.login
'),
312 $this->conf->get('credentials
.salt
')
315 $this->conf->write($this->isLoggedIn);
320 * New setting: theme name. If the default theme is used, nothing to do.
322 * If the user uses a custom theme, raintpl_tpl dir is updated to the parent directory,
323 * and the current theme is set as default in the theme setting.
325 * @return bool true if the update is successful, false otherwise.
327 public function updateMethodDefaultTheme()
329 // raintpl_tpl isn't the root template directory anymore
.
330 // We run the update only if this folder still contains the template files.
331 $tplDir = $this->conf
->get('resource.raintpl_tpl');
332 $tplFile = $tplDir . '/linklist.html';
333 if (!file_exists($tplFile)) {
337 $parent = dirname($tplDir);
338 $this->conf
->set('resource.raintpl_tpl', $parent);
339 $this->conf
->set('resource.theme', trim(str_replace($parent, '', $tplDir), '/'));
340 $this->conf
->write($this->isLoggedIn
);
342 // Dependency injection gore
343 RainTPL
::$tpl_dir = $tplDir;
349 * Move the file to inc/user.css to data/user.css.
351 * Note: Due to hardcoded paths, it's not unit testable. But one line of code should be fine.
353 * @return bool true if the update is successful, false otherwise.
355 public function updateMethodMoveUserCss()
357 if (!is_file('inc/user.css')) {
361 return rename('inc/user.css', 'data/user.css');
365 * * `markdown_escape` is a new setting, set to true as default.
367 * If the markdown plugin was already enabled, escaping is disabled to avoid
368 * breaking existing entries.
370 public function updateMethodEscapeMarkdown()
372 if ($this->conf
->exists('security.markdown_escape')) {
376 if (in_array('markdown', $this->conf
->get('general.enabled_plugins'))) {
377 $this->conf
->set('security.markdown_escape', false);
379 $this->conf
->set('security.markdown_escape', true);
381 $this->conf
->write($this->isLoggedIn
);
387 * Add 'http://' to Piwik URL the setting is set.
389 * @return bool true if the update is successful, false otherwise.
391 public function updateMethodPiwikUrl()
393 if (!$this->conf
->exists('plugins.PIWIK_URL') || startsWith($this->conf
->get('plugins.PIWIK_URL'), 'http')) {
397 $this->conf
->set('plugins.PIWIK_URL', 'http://' . $this->conf
->get('plugins.PIWIK_URL'));
398 $this->conf
->write($this->isLoggedIn
);
404 * Use ATOM feed as default.
406 public function updateMethodAtomDefault()
408 if (!$this->conf
->exists('feed.show_atom') || $this->conf
->get('feed.show_atom') === true) {
412 $this->conf
->set('feed.show_atom', true);
413 $this->conf
->write($this->isLoggedIn
);
419 * Update updates.check_updates_branch setting.
421 * If the current major version digit matches the latest branch
422 * major version digit, we set the branch to `latest`,
423 * otherwise we'll check updates on the `stable` branch.
425 * No update required for the dev version.
427 * Note: due to hardcoded URL and lack of dependency injection, this is not unit testable.
429 * FIXME! This needs to be removed when we switch to first digit major version
430 * instead of the second one since the versionning process will change.
432 public function updateMethodCheckUpdateRemoteBranch()
434 if (SHAARLI_VERSION
=== 'dev' || $this->conf
->get('updates.check_updates_branch') === 'latest') {
438 // Get latest branch major version digit
439 $latestVersion = ApplicationUtils
::getLatestGitVersionCode(
440 'https://raw.githubusercontent.com/shaarli/Shaarli/latest/shaarli_version.php',
443 if (preg_match('/(\d+)\.\d+$/', $latestVersion, $matches) === false) {
446 $latestMajor = $matches[1];
448 // Get current major version digit
449 preg_match('/(\d+)\.\d+$/', SHAARLI_VERSION
, $matches);
450 $currentMajor = $matches[1];
452 if ($currentMajor === $latestMajor) {
457 $this->conf
->set('updates.check_updates_branch', $branch);
458 $this->conf
->write($this->isLoggedIn
);
463 * Reset history store file due to date format change.
465 public function updateMethodResetHistoryFile()
467 if (is_file($this->conf
->get('resource.history'))) {
468 unlink($this->conf
->get('resource.history'));
474 * Save the datastore -> the link order is now applied when bookmarks are saved.
476 public function updateMethodReorderDatastore()
478 $this->linkDB
->save($this->conf
->get('resource.page_cache'));
483 * Change privateonly session key to visibility.
485 public function updateMethodVisibilitySession()
487 if (isset($_SESSION['privateonly'])) {
488 unset($_SESSION['privateonly']);
489 $_SESSION['visibility'] = 'private';
495 * Add download size and timeout to the configuration file
497 * @return bool true if the update is successful, false otherwise.
499 public function updateMethodDownloadSizeAndTimeoutConf()
501 if ($this->conf
->exists('general.download_max_size')
502 && $this->conf
->exists('general.download_timeout')
507 if (!$this->conf
->exists('general.download_max_size')) {
508 $this->conf
->set('general.download_max_size', 1024 * 1024 * 4);
511 if (!$this->conf
->exists('general.download_timeout')) {
512 $this->conf
->set('general.download_timeout', 30);
515 $this->conf
->write($this->isLoggedIn
);
520 * * Move thumbnails management to WebThumbnailer, coming with new settings.
522 public function updateMethodWebThumbnailer()
524 if ($this->conf
->exists('thumbnails.mode')) {
528 $thumbnailsEnabled = extension_loaded('gd') && $this->conf
->get('thumbnail.enable_thumbnails', true);
529 $this->conf
->set('thumbnails.mode', $thumbnailsEnabled ? Thumbnailer
::MODE_ALL
: Thumbnailer
::MODE_NONE
);
530 $this->conf
->set('thumbnails.width', 125);
531 $this->conf
->set('thumbnails.height', 90);
532 $this->conf
->remove('thumbnail');
533 $this->conf
->write(true);
535 if ($thumbnailsEnabled) {
536 $this->session
['warnings'][] = t(
537 t('You have enabled or changed thumbnails mode.') .
538 '<a href="./admin/thumbnails">' . t('Please synchronize them.') . '</a>'
546 * Set sticky = false on all bookmarks
548 * @return bool true if the update is successful, false otherwise.
550 public function updateMethodSetSticky()
552 foreach ($this->linkDB
as $key => $link) {
553 if (isset($link['sticky'])) {
556 $link['sticky'] = false;
557 $this->linkDB
[$key] = $link;
560 $this->linkDB
->save($this->conf
->get('resource.page_cache'));
566 * Remove redirector settings.
568 public function updateMethodRemoveRedirector()
570 $this->conf
->remove('redirector');
571 $this->conf
->write(true);
576 * Migrate the legacy arrays to Bookmark objects.
577 * Also make a backup of the datastore.
579 public function updateMethodMigrateDatabase()
581 $save = $this->conf
->get('resource.data_dir') . '/datastore.' . date('YmdHis') . '_1.php';
582 if (! copy($this->conf
->get('resource.datastore'), $save)) {
583 die('Could not backup the datastore.');
586 $linksArray = new BookmarkArray();
587 foreach ($this->linkDB
as $key => $link) {
588 $linksArray[$key] = (new Bookmark())->fromArray($link);
590 $linksIo = new BookmarkIO($this->conf
);
591 $linksIo->write($linksArray);
597 * Write the `formatter` setting in config file.
598 * Use markdown if the markdown plugin is enabled, the default one otherwise.
599 * Also remove markdown plugin setting as it is now integrated to the core.
601 public function updateMethodFormatterSetting()
603 if (!$this->conf
->exists('formatter') || $this->conf
->get('formatter') === 'default') {
604 $enabledPlugins = $this->conf
->get('general.enabled_plugins');
605 if (($pos = array_search('markdown', $enabledPlugins)) !== false) {
606 $formatter = 'markdown';
607 unset($enabledPlugins[$pos]);
608 $this->conf
->set('general.enabled_plugins', array_values($enabledPlugins));
610 $formatter = 'default';
612 $this->conf
->set('formatter', $formatter);
613 $this->conf
->write(true);