3 use Shaarli\Bookmark\LinkDB
;
4 use Shaarli\Config\ConfigJson
;
5 use Shaarli\Config\ConfigPhp
;
6 use Shaarli\Config\ConfigManager
;
7 use Shaarli\Exceptions\IOException
;
8 use Shaarli\Thumbnailer
;
12 * Used to update stuff when a new Shaarli's version is reached.
13 * Update methods are ran only once, and the stored in a JSON file.
18 * @var array Updates which are already done.
20 protected $doneUpdates;
23 * @var LinkDB instance.
28 * @var ConfigManager $conf Configuration Manager instance.
33 * @var bool True if the user is logged in, false otherwise.
35 protected $isLoggedIn;
38 * @var array $_SESSION
43 * @var ReflectionMethod[] List of current class methods.
50 * @param array $doneUpdates Updates which are already done.
51 * @param LinkDB $linkDB LinkDB instance.
52 * @param ConfigManager $conf Configuration Manager instance.
53 * @param boolean $isLoggedIn True if the user is logged in.
54 * @param array $session $_SESSION (by reference)
56 * @throws ReflectionException
58 public function __construct($doneUpdates, $linkDB, $conf, $isLoggedIn, &$session = [])
60 $this->doneUpdates
= $doneUpdates;
61 $this->linkDB
= $linkDB;
63 $this->isLoggedIn
= $isLoggedIn;
64 $this->session
= &$session;
66 // Retrieve all update methods.
67 $class = new ReflectionClass($this);
68 $this->methods
= $class->getMethods();
72 * Run all new updates.
73 * Update methods have to start with 'updateMethod' and return true (on success).
75 * @return array An array containing ran updates.
77 * @throws UpdaterException If something went wrong.
79 public function update()
81 $updatesRan = array();
83 // If the user isn't logged in, exit without updating.
84 if ($this->isLoggedIn
!== true) {
88 if ($this->methods
=== null) {
89 throw new UpdaterException(t('Couldn\'t retrieve Updater class methods.'));
92 foreach ($this->methods
as $method) {
93 // Not an update method or already done, pass.
94 if (! startsWith($method->getName(), 'updateMethod')
95 || in_array($method->getName(), $this->doneUpdates
)
101 $method->setAccessible(true);
102 $res = $method->invoke($this);
103 // Update method must return true to be considered processed.
105 $updatesRan[] = $method->getName();
107 } catch (Exception
$e) {
108 throw new UpdaterException($method, $e);
112 $this->doneUpdates
= array_merge($this->doneUpdates
, $updatesRan);
118 * @return array Updates methods already processed.
120 public function getDoneUpdates()
122 return $this->doneUpdates
;
126 * Move deprecated options.php to config.php.
128 * Milestone 0.9 (old versioning) - shaarli/Shaarli#41:
129 * options.php is not supported anymore.
131 public function updateMethodMergeDeprecatedConfigFile()
133 if (is_file($this->conf
->get('resource.data_dir') . '/options.php')) {
134 include $this->conf
->get('resource.data_dir') . '/options.php';
136 // Load GLOBALS into config
137 $allowedKeys = array_merge(ConfigPhp
::$ROOT_KEYS);
138 $allowedKeys[] = 'config';
139 foreach ($GLOBALS as $key => $value) {
140 if (in_array($key, $allowedKeys)) {
141 $this->conf
->set($key, $value);
144 $this->conf
->write($this->isLoggedIn
);
145 unlink($this->conf
->get('resource.data_dir').'/options.php');
152 * Move old configuration in PHP to the new config system in JSON format.
154 * Will rename 'config.php' into 'config.save.php' and create 'config.json.php'.
155 * It will also convert legacy setting keys to the new ones.
157 public function updateMethodConfigToJson()
159 // JSON config already exists, nothing to do.
160 if ($this->conf
->getConfigIO() instanceof ConfigJson
) {
164 $configPhp = new ConfigPhp();
165 $configJson = new ConfigJson();
166 $oldConfig = $configPhp->read($this->conf
->getConfigFile() . '.php');
167 rename($this->conf
->getConfigFileExt(), $this->conf
->getConfigFile() . '.save.php');
168 $this->conf
->setConfigIO($configJson);
169 $this->conf
->reload();
171 $legacyMap = array_flip(ConfigPhp
::$LEGACY_KEYS_MAPPING);
172 foreach (ConfigPhp
::$ROOT_KEYS as $key) {
173 $this->conf
->set($legacyMap[$key], $oldConfig[$key]);
176 // Set sub config keys (config and plugins)
177 $subConfig = array('config', 'plugins');
178 foreach ($subConfig as $sub) {
179 foreach ($oldConfig[$sub] as $key => $value) {
180 if (isset($legacyMap[$sub .'.'. $key])) {
181 $configKey = $legacyMap[$sub .'.'. $key];
183 $configKey = $sub .'.'. $key;
185 $this->conf
->set($configKey, $value);
190 $this->conf
->write($this->isLoggedIn
);
192 } catch (IOException
$e) {
193 error_log($e->getMessage());
199 * Escape settings which have been manually escaped in every request in previous versions:
201 * - general.header_link
204 * @return bool true if the update is successful, false otherwise.
206 public function updateMethodEscapeUnescapedConfig()
209 $this->conf
->set('general.title', escape($this->conf
->get('general.title')));
210 $this->conf
->set('general.header_link', escape($this->conf
->get('general.header_link')));
211 $this->conf
->set('redirector.url', escape($this->conf
->get('redirector.url')));
212 $this->conf
->write($this->isLoggedIn
);
213 } catch (Exception
$e) {
214 error_log($e->getMessage());
221 * Update the database to use the new ID system, which replaces linkdate primary keys.
222 * Also, creation and update dates are now DateTime objects (done by LinkDB).
224 * Since this update is very sensitve (changing the whole database), the datastore will be
225 * automatically backed up into the file datastore.<datetime>.php.
227 * LinkDB also adds the field 'shorturl' with the precedent format (linkdate smallhash),
228 * which will be saved by this method.
230 * @return bool true if the update is successful, false otherwise.
232 public function updateMethodDatastoreIds()
234 // up to date database
235 if (isset($this->linkDB
[0])) {
239 $save = $this->conf
->get('resource.data_dir') .'/datastore.'. date('YmdHis') .'.php';
240 copy($this->conf
->get('resource.datastore'), $save);
243 foreach ($this->linkDB
as $offset => $value) {
245 unset($this->linkDB
[$offset]);
247 $links = array_reverse($links);
249 foreach ($links as $l) {
250 unset($l['linkdate']);
252 $this->linkDB
[$cpt++
] = $l;
255 $this->linkDB
->save($this->conf
->get('resource.page_cache'));
256 $this->linkDB
->reorder();
262 * Rename tags starting with a '-' to work with tag exclusion search.
264 public function updateMethodRenameDashTags()
266 $linklist = $this->linkDB
->filterSearch();
267 foreach ($linklist as $key => $link) {
268 $link['tags'] = preg_replace('/(^| )\-/', '$1', $link['tags
']);
269 $link['tags
'] = implode(' ', array_unique(LinkFilter::tagsStrToArray($link['tags
'], true)));
270 $this->linkDB[$key] = $link;
272 $this->linkDB->save($this->conf->get('resource.page_cache
'));
277 * Initialize API settings:
278 * - api.enabled: true
279 * - api.secret: generated secret
281 public function updateMethodApiSettings()
283 if ($this->conf->exists('api
.secret
')) {
287 $this->conf->set('api
.enabled
', true);
291 $this->conf->get('credentials
.login
'),
292 $this->conf->get('credentials
.salt
')
295 $this->conf->write($this->isLoggedIn);
300 * New setting: theme name. If the default theme is used, nothing to do.
302 * If the user uses a custom theme, raintpl_tpl dir is updated to the parent directory,
303 * and the current theme is set as default in the theme setting.
305 * @return bool true if the update is successful, false otherwise.
307 public function updateMethodDefaultTheme()
309 // raintpl_tpl isn't the root template directory anymore
.
310 // We run the update only if this folder still contains the template files.
311 $tplDir = $this->conf
->get('resource.raintpl_tpl');
312 $tplFile = $tplDir . '/linklist.html';
313 if (! file_exists($tplFile)) {
317 $parent = dirname($tplDir);
318 $this->conf
->set('resource.raintpl_tpl', $parent);
319 $this->conf
->set('resource.theme', trim(str_replace($parent, '', $tplDir), '/'));
320 $this->conf
->write($this->isLoggedIn
);
322 // Dependency injection gore
323 RainTPL
::$tpl_dir = $tplDir;
329 * Move the file to inc/user.css to data/user.css.
331 * Note: Due to hardcoded paths, it's not unit testable. But one line of code should be fine.
333 * @return bool true if the update is successful, false otherwise.
335 public function updateMethodMoveUserCss()
337 if (! is_file('inc/user.css')) {
341 return rename('inc/user.css', 'data/user.css');
345 * * `markdown_escape` is a new setting, set to true as default.
347 * If the markdown plugin was already enabled, escaping is disabled to avoid
348 * breaking existing entries.
350 public function updateMethodEscapeMarkdown()
352 if ($this->conf
->exists('security.markdown_escape')) {
356 if (in_array('markdown', $this->conf
->get('general.enabled_plugins'))) {
357 $this->conf
->set('security.markdown_escape', false);
359 $this->conf
->set('security.markdown_escape', true);
361 $this->conf
->write($this->isLoggedIn
);
367 * Add 'http://' to Piwik URL the setting is set.
369 * @return bool true if the update is successful, false otherwise.
371 public function updateMethodPiwikUrl()
373 if (! $this->conf
->exists('plugins.PIWIK_URL') || startsWith($this->conf
->get('plugins.PIWIK_URL'), 'http')) {
377 $this->conf
->set('plugins.PIWIK_URL', 'http://'. $this->conf
->get('plugins.PIWIK_URL'));
378 $this->conf
->write($this->isLoggedIn
);
384 * Use ATOM feed as default.
386 public function updateMethodAtomDefault()
388 if (!$this->conf
->exists('feed.show_atom') || $this->conf
->get('feed.show_atom') === true) {
392 $this->conf
->set('feed.show_atom', true);
393 $this->conf
->write($this->isLoggedIn
);
399 * Update updates.check_updates_branch setting.
401 * If the current major version digit matches the latest branch
402 * major version digit, we set the branch to `latest`,
403 * otherwise we'll check updates on the `stable` branch.
405 * No update required for the dev version.
407 * Note: due to hardcoded URL and lack of dependency injection, this is not unit testable.
409 * FIXME! This needs to be removed when we switch to first digit major version
410 * instead of the second one since the versionning process will change.
412 public function updateMethodCheckUpdateRemoteBranch()
414 if (SHAARLI_VERSION
=== 'dev' || $this->conf
->get('updates.check_updates_branch') === 'latest') {
418 // Get latest branch major version digit
419 $latestVersion = ApplicationUtils
::getLatestGitVersionCode(
420 'https://raw.githubusercontent.com/shaarli/Shaarli/latest/shaarli_version.php',
423 if (preg_match('/(\d+)\.\d+$/', $latestVersion, $matches) === false) {
426 $latestMajor = $matches[1];
428 // Get current major version digit
429 preg_match('/(\d+)\.\d+$/', SHAARLI_VERSION
, $matches);
430 $currentMajor = $matches[1];
432 if ($currentMajor === $latestMajor) {
437 $this->conf
->set('updates.check_updates_branch', $branch);
438 $this->conf
->write($this->isLoggedIn
);
443 * Reset history store file due to date format change.
445 public function updateMethodResetHistoryFile()
447 if (is_file($this->conf
->get('resource.history'))) {
448 unlink($this->conf
->get('resource.history'));
454 * Save the datastore -> the link order is now applied when links are saved.
456 public function updateMethodReorderDatastore()
458 $this->linkDB
->save($this->conf
->get('resource.page_cache'));
463 * Change privateonly session key to visibility.
465 public function updateMethodVisibilitySession()
467 if (isset($_SESSION['privateonly'])) {
468 unset($_SESSION['privateonly']);
469 $_SESSION['visibility'] = 'private';
475 * Add download size and timeout to the configuration file
477 * @return bool true if the update is successful, false otherwise.
479 public function updateMethodDownloadSizeAndTimeoutConf()
481 if ($this->conf
->exists('general.download_max_size')
482 && $this->conf
->exists('general.download_timeout')
487 if (! $this->conf
->exists('general.download_max_size')) {
488 $this->conf
->set('general.download_max_size', 1024*1024*4);
491 if (! $this->conf
->exists('general.download_timeout')) {
492 $this->conf
->set('general.download_timeout', 30);
495 $this->conf
->write($this->isLoggedIn
);
500 * * Move thumbnails management to WebThumbnailer, coming with new settings.
502 public function updateMethodWebThumbnailer()
504 if ($this->conf
->exists('thumbnails.mode')) {
508 $thumbnailsEnabled = extension_loaded('gd') && $this->conf
->get('thumbnail.enable_thumbnails', true);
509 $this->conf
->set('thumbnails.mode', $thumbnailsEnabled ? Thumbnailer
::MODE_ALL
: Thumbnailer
::MODE_NONE
);
510 $this->conf
->set('thumbnails.width', 125);
511 $this->conf
->set('thumbnails.height', 90);
512 $this->conf
->remove('thumbnail');
513 $this->conf
->write(true);
515 if ($thumbnailsEnabled) {
516 $this->session
['warnings'][] = t(
517 'You have enabled or changed thumbnails mode. <a href="?do=thumbs_update">Please synchronize them</a>.'
525 * Set sticky = false on all links
527 * @return bool true if the update is successful, false otherwise.
529 public function updateMethodSetSticky()
531 foreach ($this->linkDB
as $key => $link) {
532 if (isset($link['sticky'])) {
535 $link['sticky'] = false;
536 $this->linkDB
[$key] = $link;
539 $this->linkDB
->save($this->conf
->get('resource.page_cache'));
546 * Class UpdaterException.
548 class UpdaterException
extends Exception
551 * @var string Method where the error occurred.
556 * @var Exception The parent exception.
563 * @param string $message Force the error message if set.
564 * @param string $method Method where the error occurred.
565 * @param Exception|bool $previous Parent exception.
567 public function __construct($message = '', $method = '', $previous = false)
569 $this->method
= $method;
570 $this->previous
= $previous;
571 $this->message
= $this->buildMessage($message);
575 * Build the exception error message.
577 * @param string $message Optional given error message.
579 * @return string The built error message.
581 private function buildMessage($message)
584 if (! empty($message)) {
585 $out .= $message . PHP_EOL
;
588 if (! empty($this->method
)) {
589 $out .= t('An error occurred while running the update ') . $this->method
. PHP_EOL
;
592 if (! empty($this->previous
)) {
593 $out .= ' '. $this->previous
->getMessage();
601 * Read the updates file, and return already done updates.
603 * @param string $updatesFilepath Updates file path.
605 * @return array Already done update methods.
607 function read_updates_file($updatesFilepath)
609 if (! empty($updatesFilepath) && is_file($updatesFilepath)) {
610 $content = file_get_contents($updatesFilepath);
611 if (! empty($content)) {
612 return explode(';', $content);
619 * Write updates file.
621 * @param string $updatesFilepath Updates file path.
622 * @param array $updates Updates array to write.
624 * @throws Exception Couldn't write version number.
626 function write_updates_file($updatesFilepath, $updates)
628 if (empty($updatesFilepath)) {
629 throw new Exception(t('Updates file path is not set, can\'t write updates.'));
632 $res = file_put_contents($updatesFilepath, implode(';', $updates));
633 if ($res === false) {
634 throw new Exception(t('Unable to write updates in '. $updatesFilepath . '.'));