3 use Shaarli\Bookmark\LinkDB
;
4 use Shaarli\Bookmark\LinkFilter
;
5 use Shaarli\Config\ConfigJson
;
6 use Shaarli\Config\ConfigPhp
;
7 use Shaarli\Config\ConfigManager
;
8 use Shaarli\Exceptions\IOException
;
9 use Shaarli\Thumbnailer
;
13 * Used to update stuff when a new Shaarli's version is reached.
14 * Update methods are ran only once, and the stored in a JSON file.
19 * @var array Updates which are already done.
21 protected $doneUpdates;
24 * @var LinkDB instance.
29 * @var ConfigManager $conf Configuration Manager instance.
34 * @var bool True if the user is logged in, false otherwise.
36 protected $isLoggedIn;
39 * @var array $_SESSION
44 * @var ReflectionMethod[] List of current class methods.
51 * @param array $doneUpdates Updates which are already done.
52 * @param LinkDB $linkDB LinkDB instance.
53 * @param ConfigManager $conf Configuration Manager instance.
54 * @param boolean $isLoggedIn True if the user is logged in.
55 * @param array $session $_SESSION (by reference)
57 * @throws ReflectionException
59 public function __construct($doneUpdates, $linkDB, $conf, $isLoggedIn, &$session = [])
61 $this->doneUpdates
= $doneUpdates;
62 $this->linkDB
= $linkDB;
64 $this->isLoggedIn
= $isLoggedIn;
65 $this->session
= &$session;
67 // Retrieve all update methods.
68 $class = new ReflectionClass($this);
69 $this->methods
= $class->getMethods();
73 * Run all new updates.
74 * Update methods have to start with 'updateMethod' and return true (on success).
76 * @return array An array containing ran updates.
78 * @throws UpdaterException If something went wrong.
80 public function update()
82 $updatesRan = array();
84 // If the user isn't logged in, exit without updating.
85 if ($this->isLoggedIn
!== true) {
89 if ($this->methods
=== null) {
90 throw new UpdaterException(t('Couldn\'t retrieve Updater class methods.'));
93 foreach ($this->methods
as $method) {
94 // Not an update method or already done, pass.
95 if (! startsWith($method->getName(), 'updateMethod')
96 || in_array($method->getName(), $this->doneUpdates
)
102 $method->setAccessible(true);
103 $res = $method->invoke($this);
104 // Update method must return true to be considered processed.
106 $updatesRan[] = $method->getName();
108 } catch (Exception
$e) {
109 throw new UpdaterException($method, $e);
113 $this->doneUpdates
= array_merge($this->doneUpdates
, $updatesRan);
119 * @return array Updates methods already processed.
121 public function getDoneUpdates()
123 return $this->doneUpdates
;
127 * Move deprecated options.php to config.php.
129 * Milestone 0.9 (old versioning) - shaarli/Shaarli#41:
130 * options.php is not supported anymore.
132 public function updateMethodMergeDeprecatedConfigFile()
134 if (is_file($this->conf
->get('resource.data_dir') . '/options.php')) {
135 include $this->conf
->get('resource.data_dir') . '/options.php';
137 // Load GLOBALS into config
138 $allowedKeys = array_merge(ConfigPhp
::$ROOT_KEYS);
139 $allowedKeys[] = 'config';
140 foreach ($GLOBALS as $key => $value) {
141 if (in_array($key, $allowedKeys)) {
142 $this->conf
->set($key, $value);
145 $this->conf
->write($this->isLoggedIn
);
146 unlink($this->conf
->get('resource.data_dir').'/options.php');
153 * Move old configuration in PHP to the new config system in JSON format.
155 * Will rename 'config.php' into 'config.save.php' and create 'config.json.php'.
156 * It will also convert legacy setting keys to the new ones.
158 public function updateMethodConfigToJson()
160 // JSON config already exists, nothing to do.
161 if ($this->conf
->getConfigIO() instanceof ConfigJson
) {
165 $configPhp = new ConfigPhp();
166 $configJson = new ConfigJson();
167 $oldConfig = $configPhp->read($this->conf
->getConfigFile() . '.php');
168 rename($this->conf
->getConfigFileExt(), $this->conf
->getConfigFile() . '.save.php');
169 $this->conf
->setConfigIO($configJson);
170 $this->conf
->reload();
172 $legacyMap = array_flip(ConfigPhp
::$LEGACY_KEYS_MAPPING);
173 foreach (ConfigPhp
::$ROOT_KEYS as $key) {
174 $this->conf
->set($legacyMap[$key], $oldConfig[$key]);
177 // Set sub config keys (config and plugins)
178 $subConfig = array('config', 'plugins');
179 foreach ($subConfig as $sub) {
180 foreach ($oldConfig[$sub] as $key => $value) {
181 if (isset($legacyMap[$sub .'.'. $key])) {
182 $configKey = $legacyMap[$sub .'.'. $key];
184 $configKey = $sub .'.'. $key;
186 $this->conf
->set($configKey, $value);
191 $this->conf
->write($this->isLoggedIn
);
193 } catch (IOException
$e) {
194 error_log($e->getMessage());
200 * Escape settings which have been manually escaped in every request in previous versions:
202 * - general.header_link
205 * @return bool true if the update is successful, false otherwise.
207 public function updateMethodEscapeUnescapedConfig()
210 $this->conf
->set('general.title', escape($this->conf
->get('general.title')));
211 $this->conf
->set('general.header_link', escape($this->conf
->get('general.header_link')));
212 $this->conf
->set('redirector.url', escape($this->conf
->get('redirector.url')));
213 $this->conf
->write($this->isLoggedIn
);
214 } catch (Exception
$e) {
215 error_log($e->getMessage());
222 * Update the database to use the new ID system, which replaces linkdate primary keys.
223 * Also, creation and update dates are now DateTime objects (done by LinkDB).
225 * Since this update is very sensitve (changing the whole database), the datastore will be
226 * automatically backed up into the file datastore.<datetime>.php.
228 * LinkDB also adds the field 'shorturl' with the precedent format (linkdate smallhash),
229 * which will be saved by this method.
231 * @return bool true if the update is successful, false otherwise.
233 public function updateMethodDatastoreIds()
235 // up to date database
236 if (isset($this->linkDB
[0])) {
240 $save = $this->conf
->get('resource.data_dir') .'/datastore.'. date('YmdHis') .'.php';
241 copy($this->conf
->get('resource.datastore'), $save);
244 foreach ($this->linkDB
as $offset => $value) {
246 unset($this->linkDB
[$offset]);
248 $links = array_reverse($links);
250 foreach ($links as $l) {
251 unset($l['linkdate']);
253 $this->linkDB
[$cpt++
] = $l;
256 $this->linkDB
->save($this->conf
->get('resource.page_cache'));
257 $this->linkDB
->reorder();
263 * Rename tags starting with a '-' to work with tag exclusion search.
265 public function updateMethodRenameDashTags()
267 $linklist = $this->linkDB
->filterSearch();
268 foreach ($linklist as $key => $link) {
269 $link['tags'] = preg_replace('/(^| )\-/', '$1', $link['tags
']);
270 $link['tags
'] = implode(' ', array_unique(LinkFilter::tagsStrToArray($link['tags
'], true)));
271 $this->linkDB[$key] = $link;
273 $this->linkDB->save($this->conf->get('resource.page_cache
'));
278 * Initialize API settings:
279 * - api.enabled: true
280 * - api.secret: generated secret
282 public function updateMethodApiSettings()
284 if ($this->conf->exists('api
.secret
')) {
288 $this->conf->set('api
.enabled
', true);
292 $this->conf->get('credentials
.login
'),
293 $this->conf->get('credentials
.salt
')
296 $this->conf->write($this->isLoggedIn);
301 * New setting: theme name. If the default theme is used, nothing to do.
303 * If the user uses a custom theme, raintpl_tpl dir is updated to the parent directory,
304 * and the current theme is set as default in the theme setting.
306 * @return bool true if the update is successful, false otherwise.
308 public function updateMethodDefaultTheme()
310 // raintpl_tpl isn't the root template directory anymore
.
311 // We run the update only if this folder still contains the template files.
312 $tplDir = $this->conf
->get('resource.raintpl_tpl');
313 $tplFile = $tplDir . '/linklist.html';
314 if (! file_exists($tplFile)) {
318 $parent = dirname($tplDir);
319 $this->conf
->set('resource.raintpl_tpl', $parent);
320 $this->conf
->set('resource.theme', trim(str_replace($parent, '', $tplDir), '/'));
321 $this->conf
->write($this->isLoggedIn
);
323 // Dependency injection gore
324 RainTPL
::$tpl_dir = $tplDir;
330 * Move the file to inc/user.css to data/user.css.
332 * Note: Due to hardcoded paths, it's not unit testable. But one line of code should be fine.
334 * @return bool true if the update is successful, false otherwise.
336 public function updateMethodMoveUserCss()
338 if (! is_file('inc/user.css')) {
342 return rename('inc/user.css', 'data/user.css');
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
);
368 * Add 'http://' to Piwik URL the setting is set.
370 * @return bool true if the update is successful, false otherwise.
372 public function updateMethodPiwikUrl()
374 if (! $this->conf
->exists('plugins.PIWIK_URL') || startsWith($this->conf
->get('plugins.PIWIK_URL'), 'http')) {
378 $this->conf
->set('plugins.PIWIK_URL', 'http://'. $this->conf
->get('plugins.PIWIK_URL'));
379 $this->conf
->write($this->isLoggedIn
);
385 * Use ATOM feed as default.
387 public function updateMethodAtomDefault()
389 if (!$this->conf
->exists('feed.show_atom') || $this->conf
->get('feed.show_atom') === true) {
393 $this->conf
->set('feed.show_atom', true);
394 $this->conf
->write($this->isLoggedIn
);
400 * Update updates.check_updates_branch setting.
402 * If the current major version digit matches the latest branch
403 * major version digit, we set the branch to `latest`,
404 * otherwise we'll check updates on the `stable` branch.
406 * No update required for the dev version.
408 * Note: due to hardcoded URL and lack of dependency injection, this is not unit testable.
410 * FIXME! This needs to be removed when we switch to first digit major version
411 * instead of the second one since the versionning process will change.
413 public function updateMethodCheckUpdateRemoteBranch()
415 if (SHAARLI_VERSION
=== 'dev' || $this->conf
->get('updates.check_updates_branch') === 'latest') {
419 // Get latest branch major version digit
420 $latestVersion = ApplicationUtils
::getLatestGitVersionCode(
421 'https://raw.githubusercontent.com/shaarli/Shaarli/latest/shaarli_version.php',
424 if (preg_match('/(\d+)\.\d+$/', $latestVersion, $matches) === false) {
427 $latestMajor = $matches[1];
429 // Get current major version digit
430 preg_match('/(\d+)\.\d+$/', SHAARLI_VERSION
, $matches);
431 $currentMajor = $matches[1];
433 if ($currentMajor === $latestMajor) {
438 $this->conf
->set('updates.check_updates_branch', $branch);
439 $this->conf
->write($this->isLoggedIn
);
444 * Reset history store file due to date format change.
446 public function updateMethodResetHistoryFile()
448 if (is_file($this->conf
->get('resource.history'))) {
449 unlink($this->conf
->get('resource.history'));
455 * Save the datastore -> the link order is now applied when links are saved.
457 public function updateMethodReorderDatastore()
459 $this->linkDB
->save($this->conf
->get('resource.page_cache'));
464 * Change privateonly session key to visibility.
466 public function updateMethodVisibilitySession()
468 if (isset($_SESSION['privateonly'])) {
469 unset($_SESSION['privateonly']);
470 $_SESSION['visibility'] = 'private';
476 * Add download size and timeout to the configuration file
478 * @return bool true if the update is successful, false otherwise.
480 public function updateMethodDownloadSizeAndTimeoutConf()
482 if ($this->conf
->exists('general.download_max_size')
483 && $this->conf
->exists('general.download_timeout')
488 if (! $this->conf
->exists('general.download_max_size')) {
489 $this->conf
->set('general.download_max_size', 1024*1024*4);
492 if (! $this->conf
->exists('general.download_timeout')) {
493 $this->conf
->set('general.download_timeout', 30);
496 $this->conf
->write($this->isLoggedIn
);
501 * * Move thumbnails management to WebThumbnailer, coming with new settings.
503 public function updateMethodWebThumbnailer()
505 if ($this->conf
->exists('thumbnails.mode')) {
509 $thumbnailsEnabled = extension_loaded('gd') && $this->conf
->get('thumbnail.enable_thumbnails', true);
510 $this->conf
->set('thumbnails.mode', $thumbnailsEnabled ? Thumbnailer
::MODE_ALL
: Thumbnailer
::MODE_NONE
);
511 $this->conf
->set('thumbnails.width', 125);
512 $this->conf
->set('thumbnails.height', 90);
513 $this->conf
->remove('thumbnail');
514 $this->conf
->write(true);
516 if ($thumbnailsEnabled) {
517 $this->session
['warnings'][] = t(
518 'You have enabled or changed thumbnails mode. <a href="?do=thumbs_update">Please synchronize them</a>.'
526 * Set sticky = false on all links
528 * @return bool true if the update is successful, false otherwise.
530 public function updateMethodSetSticky()
532 foreach ($this->linkDB
as $key => $link) {
533 if (isset($link['sticky'])) {
536 $link['sticky'] = false;
537 $this->linkDB
[$key] = $link;
540 $this->linkDB
->save($this->conf
->get('resource.page_cache'));
547 * Class UpdaterException.
549 class UpdaterException
extends Exception
552 * @var string Method where the error occurred.
557 * @var Exception The parent exception.
564 * @param string $message Force the error message if set.
565 * @param string $method Method where the error occurred.
566 * @param Exception|bool $previous Parent exception.
568 public function __construct($message = '', $method = '', $previous = false)
570 $this->method
= $method;
571 $this->previous
= $previous;
572 $this->message
= $this->buildMessage($message);
576 * Build the exception error message.
578 * @param string $message Optional given error message.
580 * @return string The built error message.
582 private function buildMessage($message)
585 if (! empty($message)) {
586 $out .= $message . PHP_EOL
;
589 if (! empty($this->method
)) {
590 $out .= t('An error occurred while running the update ') . $this->method
. PHP_EOL
;
593 if (! empty($this->previous
)) {
594 $out .= ' '. $this->previous
->getMessage();
602 * Read the updates file, and return already done updates.
604 * @param string $updatesFilepath Updates file path.
606 * @return array Already done update methods.
608 function read_updates_file($updatesFilepath)
610 if (! empty($updatesFilepath) && is_file($updatesFilepath)) {
611 $content = file_get_contents($updatesFilepath);
612 if (! empty($content)) {
613 return explode(';', $content);
620 * Write updates file.
622 * @param string $updatesFilepath Updates file path.
623 * @param array $updates Updates array to write.
625 * @throws Exception Couldn't write version number.
627 function write_updates_file($updatesFilepath, $updates)
629 if (empty($updatesFilepath)) {
630 throw new Exception(t('Updates file path is not set, can\'t write updates.'));
633 $res = file_put_contents($updatesFilepath, implode(';', $updates));
634 if ($res === false) {
635 throw new Exception(t('Unable to write updates in '. $updatesFilepath . '.'));