2 use Shaarli\Config\ConfigJson
;
3 use Shaarli\Config\ConfigPhp
;
4 use Shaarli\Config\ConfigManager
;
5 use Shaarli\Thumbnailer
;
9 * Used to update stuff when a new Shaarli's version is reached.
10 * Update methods are ran only once, and the stored in a JSON file.
15 * @var array Updates which are already done.
17 protected $doneUpdates;
20 * @var LinkDB instance.
25 * @var ConfigManager $conf Configuration Manager instance.
30 * @var bool True if the user is logged in, false otherwise.
32 protected $isLoggedIn;
35 * @var array $_SESSION
40 * @var ReflectionMethod[] List of current class methods.
47 * @param array $doneUpdates Updates which are already done.
48 * @param LinkDB $linkDB LinkDB instance.
49 * @param ConfigManager $conf Configuration Manager instance.
50 * @param boolean $isLoggedIn True if the user is logged in.
51 * @param array $session $_SESSION (by reference)
53 * @throws ReflectionException
55 public function __construct($doneUpdates, $linkDB, $conf, $isLoggedIn, &$session = [])
57 $this->doneUpdates
= $doneUpdates;
58 $this->linkDB
= $linkDB;
60 $this->isLoggedIn
= $isLoggedIn;
61 $this->session
= &$session;
63 // Retrieve all update methods.
64 $class = new ReflectionClass($this);
65 $this->methods
= $class->getMethods();
69 * Run all new updates.
70 * Update methods have to start with 'updateMethod' and return true (on success).
72 * @return array An array containing ran updates.
74 * @throws UpdaterException If something went wrong.
76 public function update()
78 $updatesRan = array();
80 // If the user isn't logged in, exit without updating.
81 if ($this->isLoggedIn
!== true) {
85 if ($this->methods
=== null) {
86 throw new UpdaterException(t('Couldn\'t retrieve Updater class methods.'));
89 foreach ($this->methods
as $method) {
90 // Not an update method or already done, pass.
91 if (! startsWith($method->getName(), 'updateMethod')
92 || in_array($method->getName(), $this->doneUpdates
)
98 $method->setAccessible(true);
99 $res = $method->invoke($this);
100 // Update method must return true to be considered processed.
102 $updatesRan[] = $method->getName();
104 } catch (Exception
$e) {
105 throw new UpdaterException($method, $e);
109 $this->doneUpdates
= array_merge($this->doneUpdates
, $updatesRan);
115 * @return array Updates methods already processed.
117 public function getDoneUpdates()
119 return $this->doneUpdates
;
123 * Move deprecated options.php to config.php.
125 * Milestone 0.9 (old versioning) - shaarli/Shaarli#41:
126 * options.php is not supported anymore.
128 public function updateMethodMergeDeprecatedConfigFile()
130 if (is_file($this->conf
->get('resource.data_dir') . '/options.php')) {
131 include $this->conf
->get('resource.data_dir') . '/options.php';
133 // Load GLOBALS into config
134 $allowedKeys = array_merge(ConfigPhp
::$ROOT_KEYS);
135 $allowedKeys[] = 'config';
136 foreach ($GLOBALS as $key => $value) {
137 if (in_array($key, $allowedKeys)) {
138 $this->conf
->set($key, $value);
141 $this->conf
->write($this->isLoggedIn
);
142 unlink($this->conf
->get('resource.data_dir').'/options.php');
149 * Move old configuration in PHP to the new config system in JSON format.
151 * Will rename 'config.php' into 'config.save.php' and create 'config.json.php'.
152 * It will also convert legacy setting keys to the new ones.
154 public function updateMethodConfigToJson()
156 // JSON config already exists, nothing to do.
157 if ($this->conf
->getConfigIO() instanceof ConfigJson
) {
161 $configPhp = new ConfigPhp();
162 $configJson = new ConfigJson();
163 $oldConfig = $configPhp->read($this->conf
->getConfigFile() . '.php');
164 rename($this->conf
->getConfigFileExt(), $this->conf
->getConfigFile() . '.save.php');
165 $this->conf
->setConfigIO($configJson);
166 $this->conf
->reload();
168 $legacyMap = array_flip(ConfigPhp
::$LEGACY_KEYS_MAPPING);
169 foreach (ConfigPhp
::$ROOT_KEYS as $key) {
170 $this->conf
->set($legacyMap[$key], $oldConfig[$key]);
173 // Set sub config keys (config and plugins)
174 $subConfig = array('config', 'plugins');
175 foreach ($subConfig as $sub) {
176 foreach ($oldConfig[$sub] as $key => $value) {
177 if (isset($legacyMap[$sub .'.'. $key])) {
178 $configKey = $legacyMap[$sub .'.'. $key];
180 $configKey = $sub .'.'. $key;
182 $this->conf
->set($configKey, $value);
187 $this->conf
->write($this->isLoggedIn
);
189 } catch (IOException
$e) {
190 error_log($e->getMessage());
196 * Escape settings which have been manually escaped in every request in previous versions:
198 * - general.header_link
201 * @return bool true if the update is successful, false otherwise.
203 public function updateMethodEscapeUnescapedConfig()
206 $this->conf
->set('general.title', escape($this->conf
->get('general.title')));
207 $this->conf
->set('general.header_link', escape($this->conf
->get('general.header_link')));
208 $this->conf
->set('redirector.url', escape($this->conf
->get('redirector.url')));
209 $this->conf
->write($this->isLoggedIn
);
210 } catch (Exception
$e) {
211 error_log($e->getMessage());
218 * Update the database to use the new ID system, which replaces linkdate primary keys.
219 * Also, creation and update dates are now DateTime objects (done by LinkDB).
221 * Since this update is very sensitve (changing the whole database), the datastore will be
222 * automatically backed up into the file datastore.<datetime>.php.
224 * LinkDB also adds the field 'shorturl' with the precedent format (linkdate smallhash),
225 * which will be saved by this method.
227 * @return bool true if the update is successful, false otherwise.
229 public function updateMethodDatastoreIds()
231 // up to date database
232 if (isset($this->linkDB
[0])) {
236 $save = $this->conf
->get('resource.data_dir') .'/datastore.'. date('YmdHis') .'.php';
237 copy($this->conf
->get('resource.datastore'), $save);
240 foreach ($this->linkDB
as $offset => $value) {
242 unset($this->linkDB
[$offset]);
244 $links = array_reverse($links);
246 foreach ($links as $l) {
247 unset($l['linkdate']);
249 $this->linkDB
[$cpt++
] = $l;
252 $this->linkDB
->save($this->conf
->get('resource.page_cache'));
253 $this->linkDB
->reorder();
259 * Rename tags starting with a '-' to work with tag exclusion search.
261 public function updateMethodRenameDashTags()
263 $linklist = $this->linkDB
->filterSearch();
264 foreach ($linklist as $key => $link) {
265 $link['tags'] = preg_replace('/(^| )\-/', '$1', $link['tags
']);
266 $link['tags
'] = implode(' ', array_unique(LinkFilter::tagsStrToArray($link['tags
'], true)));
267 $this->linkDB[$key] = $link;
269 $this->linkDB->save($this->conf->get('resource.page_cache
'));
274 * Initialize API settings:
275 * - api.enabled: true
276 * - api.secret: generated secret
278 public function updateMethodApiSettings()
280 if ($this->conf->exists('api
.secret
')) {
284 $this->conf->set('api
.enabled
', true);
288 $this->conf->get('credentials
.login
'),
289 $this->conf->get('credentials
.salt
')
292 $this->conf->write($this->isLoggedIn);
297 * New setting: theme name. If the default theme is used, nothing to do.
299 * If the user uses a custom theme, raintpl_tpl dir is updated to the parent directory,
300 * and the current theme is set as default in the theme setting.
302 * @return bool true if the update is successful, false otherwise.
304 public function updateMethodDefaultTheme()
306 // raintpl_tpl isn't the root template directory anymore
.
307 // We run the update only if this folder still contains the template files.
308 $tplDir = $this->conf
->get('resource.raintpl_tpl');
309 $tplFile = $tplDir . '/linklist.html';
310 if (! file_exists($tplFile)) {
314 $parent = dirname($tplDir);
315 $this->conf
->set('resource.raintpl_tpl', $parent);
316 $this->conf
->set('resource.theme', trim(str_replace($parent, '', $tplDir), '/'));
317 $this->conf
->write($this->isLoggedIn
);
319 // Dependency injection gore
320 RainTPL
::$tpl_dir = $tplDir;
326 * Move the file to inc/user.css to data/user.css.
328 * Note: Due to hardcoded paths, it's not unit testable. But one line of code should be fine.
330 * @return bool true if the update is successful, false otherwise.
332 public function updateMethodMoveUserCss()
334 if (! is_file('inc/user.css')) {
338 return rename('inc/user.css', 'data/user.css');
342 * * `markdown_escape` is a new setting, set to true as default.
344 * If the markdown plugin was already enabled, escaping is disabled to avoid
345 * breaking existing entries.
347 public function updateMethodEscapeMarkdown()
349 if ($this->conf
->exists('security.markdown_escape')) {
353 if (in_array('markdown', $this->conf
->get('general.enabled_plugins'))) {
354 $this->conf
->set('security.markdown_escape', false);
356 $this->conf
->set('security.markdown_escape', true);
358 $this->conf
->write($this->isLoggedIn
);
364 * Add 'http://' to Piwik URL the setting is set.
366 * @return bool true if the update is successful, false otherwise.
368 public function updateMethodPiwikUrl()
370 if (! $this->conf
->exists('plugins.PIWIK_URL') || startsWith($this->conf
->get('plugins.PIWIK_URL'), 'http')) {
374 $this->conf
->set('plugins.PIWIK_URL', 'http://'. $this->conf
->get('plugins.PIWIK_URL'));
375 $this->conf
->write($this->isLoggedIn
);
381 * Use ATOM feed as default.
383 public function updateMethodAtomDefault()
385 if (!$this->conf
->exists('feed.show_atom') || $this->conf
->get('feed.show_atom') === true) {
389 $this->conf
->set('feed.show_atom', true);
390 $this->conf
->write($this->isLoggedIn
);
396 * Update updates.check_updates_branch setting.
398 * If the current major version digit matches the latest branch
399 * major version digit, we set the branch to `latest`,
400 * otherwise we'll check updates on the `stable` branch.
402 * No update required for the dev version.
404 * Note: due to hardcoded URL and lack of dependency injection, this is not unit testable.
406 * FIXME! This needs to be removed when we switch to first digit major version
407 * instead of the second one since the versionning process will change.
409 public function updateMethodCheckUpdateRemoteBranch()
411 if (SHAARLI_VERSION
=== 'dev' || $this->conf
->get('updates.check_updates_branch') === 'latest') {
415 // Get latest branch major version digit
416 $latestVersion = ApplicationUtils
::getLatestGitVersionCode(
417 'https://raw.githubusercontent.com/shaarli/Shaarli/latest/shaarli_version.php',
420 if (preg_match('/(\d+)\.\d+$/', $latestVersion, $matches) === false) {
423 $latestMajor = $matches[1];
425 // Get current major version digit
426 preg_match('/(\d+)\.\d+$/', SHAARLI_VERSION
, $matches);
427 $currentMajor = $matches[1];
429 if ($currentMajor === $latestMajor) {
434 $this->conf
->set('updates.check_updates_branch', $branch);
435 $this->conf
->write($this->isLoggedIn
);
440 * Reset history store file due to date format change.
442 public function updateMethodResetHistoryFile()
444 if (is_file($this->conf
->get('resource.history'))) {
445 unlink($this->conf
->get('resource.history'));
451 * Save the datastore -> the link order is now applied when links are saved.
453 public function updateMethodReorderDatastore()
455 $this->linkDB
->save($this->conf
->get('resource.page_cache'));
460 * Change privateonly session key to visibility.
462 public function updateMethodVisibilitySession()
464 if (isset($_SESSION['privateonly'])) {
465 unset($_SESSION['privateonly']);
466 $_SESSION['visibility'] = 'private';
472 * Add download size and timeout to the configuration file
474 * @return bool true if the update is successful, false otherwise.
476 public function updateMethodDownloadSizeAndTimeoutConf()
478 if ($this->conf
->exists('general.download_max_size')
479 && $this->conf
->exists('general.download_timeout')
484 if (! $this->conf
->exists('general.download_max_size')) {
485 $this->conf
->set('general.download_max_size', 1024*1024*4);
488 if (! $this->conf
->exists('general.download_timeout')) {
489 $this->conf
->set('general.download_timeout', 30);
492 $this->conf
->write($this->isLoggedIn
);
497 * * Move thumbnails management to WebThumbnailer, coming with new settings.
499 public function updateMethodWebThumbnailer()
501 if ($this->conf
->exists('thumbnails.mode')) {
505 $thumbnailsEnabled = extension_loaded('gd') && $this->conf
->get('thumbnail.enable_thumbnails', true);
506 $this->conf
->set('thumbnails.mode', $thumbnailsEnabled ? Thumbnailer
::MODE_ALL
: Thumbnailer
::MODE_NONE
);
507 $this->conf
->set('thumbnails.width', 125);
508 $this->conf
->set('thumbnails.height', 90);
509 $this->conf
->remove('thumbnail');
510 $this->conf
->write(true);
512 if ($thumbnailsEnabled) {
513 $this->session
['warnings'][] = t(
514 'You have enabled or changed thumbnails mode. <a href="?do=thumbs_update">Please synchronize them</a>.'
522 * Set sticky = false on all links
524 * @return bool true if the update is successful, false otherwise.
526 public function updateMethodSetSticky()
528 foreach ($this->linkDB
as $key => $link) {
529 if (isset($link['sticky'])) {
532 $link['sticky'] = false;
533 $this->linkDB
[$key] = $link;
536 $this->linkDB
->save($this->conf
->get('resource.page_cache'));
543 * Class UpdaterException.
545 class UpdaterException
extends Exception
548 * @var string Method where the error occurred.
553 * @var Exception The parent exception.
560 * @param string $message Force the error message if set.
561 * @param string $method Method where the error occurred.
562 * @param Exception|bool $previous Parent exception.
564 public function __construct($message = '', $method = '', $previous = false)
566 $this->method
= $method;
567 $this->previous
= $previous;
568 $this->message
= $this->buildMessage($message);
572 * Build the exception error message.
574 * @param string $message Optional given error message.
576 * @return string The built error message.
578 private function buildMessage($message)
581 if (! empty($message)) {
582 $out .= $message . PHP_EOL
;
585 if (! empty($this->method
)) {
586 $out .= t('An error occurred while running the update ') . $this->method
. PHP_EOL
;
589 if (! empty($this->previous
)) {
590 $out .= ' '. $this->previous
->getMessage();
598 * Read the updates file, and return already done updates.
600 * @param string $updatesFilepath Updates file path.
602 * @return array Already done update methods.
604 function read_updates_file($updatesFilepath)
606 if (! empty($updatesFilepath) && is_file($updatesFilepath)) {
607 $content = file_get_contents($updatesFilepath);
608 if (! empty($content)) {
609 return explode(';', $content);
616 * Write updates file.
618 * @param string $updatesFilepath Updates file path.
619 * @param array $updates Updates array to write.
621 * @throws Exception Couldn't write version number.
623 function write_updates_file($updatesFilepath, $updates)
625 if (empty($updatesFilepath)) {
626 throw new Exception(t('Updates file path is not set, can\'t write updates.'));
629 $res = file_put_contents($updatesFilepath, implode(';', $updates));
630 if ($res === false) {
631 throw new Exception(t('Unable to write updates in '. $updatesFilepath . '.'));