2 use Shaarli\Config\ConfigJson
;
3 use Shaarli\Config\ConfigPhp
;
4 use Shaarli\Config\ConfigManager
;
8 * Used to update stuff when a new Shaarli's version is reached.
9 * Update methods are ran only once, and the stored in a JSON file.
14 * @var array Updates which are already done.
16 protected $doneUpdates;
19 * @var LinkDB instance.
24 * @var ConfigManager $conf Configuration Manager instance.
29 * @var bool True if the user is logged in, false otherwise.
31 protected $isLoggedIn;
34 * @var array $_SESSION
39 * @var ReflectionMethod[] List of current class methods.
46 * @param array $doneUpdates Updates which are already done.
47 * @param LinkDB $linkDB LinkDB instance.
48 * @param ConfigManager $conf Configuration Manager instance.
49 * @param boolean $isLoggedIn True if the user is logged in.
50 * @param array $session $_SESSION (by reference)
52 * @throws ReflectionException
54 public function __construct($doneUpdates, $linkDB, $conf, $isLoggedIn, &$session = [])
56 $this->doneUpdates
= $doneUpdates;
57 $this->linkDB
= $linkDB;
59 $this->isLoggedIn
= $isLoggedIn;
60 $this->session
= &$session;
62 // Retrieve all update methods.
63 $class = new ReflectionClass($this);
64 $this->methods
= $class->getMethods();
68 * Run all new updates.
69 * Update methods have to start with 'updateMethod' and return true (on success).
71 * @return array An array containing ran updates.
73 * @throws UpdaterException If something went wrong.
75 public function update()
77 $updatesRan = array();
79 // If the user isn't logged in, exit without updating.
80 if ($this->isLoggedIn
!== true) {
84 if ($this->methods
=== null) {
85 throw new UpdaterException(t('Couldn\'t retrieve Updater class methods.'));
88 foreach ($this->methods
as $method) {
89 // Not an update method or already done, pass.
90 if (! startsWith($method->getName(), 'updateMethod')
91 || in_array($method->getName(), $this->doneUpdates
)
97 $method->setAccessible(true);
98 $res = $method->invoke($this);
99 // Update method must return true to be considered processed.
101 $updatesRan[] = $method->getName();
103 } catch (Exception
$e) {
104 throw new UpdaterException($method, $e);
108 $this->doneUpdates
= array_merge($this->doneUpdates
, $updatesRan);
114 * @return array Updates methods already processed.
116 public function getDoneUpdates()
118 return $this->doneUpdates
;
122 * Move deprecated options.php to config.php.
124 * Milestone 0.9 (old versioning) - shaarli/Shaarli#41:
125 * options.php is not supported anymore.
127 public function updateMethodMergeDeprecatedConfigFile()
129 if (is_file($this->conf
->get('resource.data_dir') . '/options.php')) {
130 include $this->conf
->get('resource.data_dir') . '/options.php';
132 // Load GLOBALS into config
133 $allowedKeys = array_merge(ConfigPhp
::$ROOT_KEYS);
134 $allowedKeys[] = 'config';
135 foreach ($GLOBALS as $key => $value) {
136 if (in_array($key, $allowedKeys)) {
137 $this->conf
->set($key, $value);
140 $this->conf
->write($this->isLoggedIn
);
141 unlink($this->conf
->get('resource.data_dir').'/options.php');
148 * Move old configuration in PHP to the new config system in JSON format.
150 * Will rename 'config.php' into 'config.save.php' and create 'config.json.php'.
151 * It will also convert legacy setting keys to the new ones.
153 public function updateMethodConfigToJson()
155 // JSON config already exists, nothing to do.
156 if ($this->conf
->getConfigIO() instanceof ConfigJson
) {
160 $configPhp = new ConfigPhp();
161 $configJson = new ConfigJson();
162 $oldConfig = $configPhp->read($this->conf
->getConfigFile() . '.php');
163 rename($this->conf
->getConfigFileExt(), $this->conf
->getConfigFile() . '.save.php');
164 $this->conf
->setConfigIO($configJson);
165 $this->conf
->reload();
167 $legacyMap = array_flip(ConfigPhp
::$LEGACY_KEYS_MAPPING);
168 foreach (ConfigPhp
::$ROOT_KEYS as $key) {
169 $this->conf
->set($legacyMap[$key], $oldConfig[$key]);
172 // Set sub config keys (config and plugins)
173 $subConfig = array('config', 'plugins');
174 foreach ($subConfig as $sub) {
175 foreach ($oldConfig[$sub] as $key => $value) {
176 if (isset($legacyMap[$sub .'.'. $key])) {
177 $configKey = $legacyMap[$sub .'.'. $key];
179 $configKey = $sub .'.'. $key;
181 $this->conf
->set($configKey, $value);
186 $this->conf
->write($this->isLoggedIn
);
188 } catch (IOException
$e) {
189 error_log($e->getMessage());
195 * Escape settings which have been manually escaped in every request in previous versions:
197 * - general.header_link
200 * @return bool true if the update is successful, false otherwise.
202 public function updateMethodEscapeUnescapedConfig()
205 $this->conf
->set('general.title', escape($this->conf
->get('general.title')));
206 $this->conf
->set('general.header_link', escape($this->conf
->get('general.header_link')));
207 $this->conf
->set('redirector.url', escape($this->conf
->get('redirector.url')));
208 $this->conf
->write($this->isLoggedIn
);
209 } catch (Exception
$e) {
210 error_log($e->getMessage());
217 * Update the database to use the new ID system, which replaces linkdate primary keys.
218 * Also, creation and update dates are now DateTime objects (done by LinkDB).
220 * Since this update is very sensitve (changing the whole database), the datastore will be
221 * automatically backed up into the file datastore.<datetime>.php.
223 * LinkDB also adds the field 'shorturl' with the precedent format (linkdate smallhash),
224 * which will be saved by this method.
226 * @return bool true if the update is successful, false otherwise.
228 public function updateMethodDatastoreIds()
230 // up to date database
231 if (isset($this->linkDB
[0])) {
235 $save = $this->conf
->get('resource.data_dir') .'/datastore.'. date('YmdHis') .'.php';
236 copy($this->conf
->get('resource.datastore'), $save);
239 foreach ($this->linkDB
as $offset => $value) {
241 unset($this->linkDB
[$offset]);
243 $links = array_reverse($links);
245 foreach ($links as $l) {
246 unset($l['linkdate']);
248 $this->linkDB
[$cpt++
] = $l;
251 $this->linkDB
->save($this->conf
->get('resource.page_cache'));
252 $this->linkDB
->reorder();
258 * Rename tags starting with a '-' to work with tag exclusion search.
260 public function updateMethodRenameDashTags()
262 $linklist = $this->linkDB
->filterSearch();
263 foreach ($linklist as $key => $link) {
264 $link['tags'] = preg_replace('/(^| )\-/', '$1', $link['tags
']);
265 $link['tags
'] = implode(' ', array_unique(LinkFilter::tagsStrToArray($link['tags
'], true)));
266 $this->linkDB[$key] = $link;
268 $this->linkDB->save($this->conf->get('resource.page_cache
'));
273 * Initialize API settings:
274 * - api.enabled: true
275 * - api.secret: generated secret
277 public function updateMethodApiSettings()
279 if ($this->conf->exists('api
.secret
')) {
283 $this->conf->set('api
.enabled
', true);
287 $this->conf->get('credentials
.login
'),
288 $this->conf->get('credentials
.salt
')
291 $this->conf->write($this->isLoggedIn);
296 * New setting: theme name. If the default theme is used, nothing to do.
298 * If the user uses a custom theme, raintpl_tpl dir is updated to the parent directory,
299 * and the current theme is set as default in the theme setting.
301 * @return bool true if the update is successful, false otherwise.
303 public function updateMethodDefaultTheme()
305 // raintpl_tpl isn't the root template directory anymore
.
306 // We run the update only if this folder still contains the template files.
307 $tplDir = $this->conf
->get('resource.raintpl_tpl');
308 $tplFile = $tplDir . '/linklist.html';
309 if (! file_exists($tplFile)) {
313 $parent = dirname($tplDir);
314 $this->conf
->set('resource.raintpl_tpl', $parent);
315 $this->conf
->set('resource.theme', trim(str_replace($parent, '', $tplDir), '/'));
316 $this->conf
->write($this->isLoggedIn
);
318 // Dependency injection gore
319 RainTPL
::$tpl_dir = $tplDir;
325 * Move the file to inc/user.css to data/user.css.
327 * Note: Due to hardcoded paths, it's not unit testable. But one line of code should be fine.
329 * @return bool true if the update is successful, false otherwise.
331 public function updateMethodMoveUserCss()
333 if (! is_file('inc/user.css')) {
337 return rename('inc/user.css', 'data/user.css');
341 * * `markdown_escape` is a new setting, set to true as default.
343 * If the markdown plugin was already enabled, escaping is disabled to avoid
344 * breaking existing entries.
346 public function updateMethodEscapeMarkdown()
348 if ($this->conf
->exists('security.markdown_escape')) {
352 if (in_array('markdown', $this->conf
->get('general.enabled_plugins'))) {
353 $this->conf
->set('security.markdown_escape', false);
355 $this->conf
->set('security.markdown_escape', true);
357 $this->conf
->write($this->isLoggedIn
);
363 * Add 'http://' to Piwik URL the setting is set.
365 * @return bool true if the update is successful, false otherwise.
367 public function updateMethodPiwikUrl()
369 if (! $this->conf
->exists('plugins.PIWIK_URL') || startsWith($this->conf
->get('plugins.PIWIK_URL'), 'http')) {
373 $this->conf
->set('plugins.PIWIK_URL', 'http://'. $this->conf
->get('plugins.PIWIK_URL'));
374 $this->conf
->write($this->isLoggedIn
);
380 * Use ATOM feed as default.
382 public function updateMethodAtomDefault()
384 if (!$this->conf
->exists('feed.show_atom') || $this->conf
->get('feed.show_atom') === true) {
388 $this->conf
->set('feed.show_atom', true);
389 $this->conf
->write($this->isLoggedIn
);
395 * Update updates.check_updates_branch setting.
397 * If the current major version digit matches the latest branch
398 * major version digit, we set the branch to `latest`,
399 * otherwise we'll check updates on the `stable` branch.
401 * No update required for the dev version.
403 * Note: due to hardcoded URL and lack of dependency injection, this is not unit testable.
405 * FIXME! This needs to be removed when we switch to first digit major version
406 * instead of the second one since the versionning process will change.
408 public function updateMethodCheckUpdateRemoteBranch()
410 if (SHAARLI_VERSION
=== 'dev' || $this->conf
->get('updates.check_updates_branch') === 'latest') {
414 // Get latest branch major version digit
415 $latestVersion = ApplicationUtils
::getLatestGitVersionCode(
416 'https://raw.githubusercontent.com/shaarli/Shaarli/latest/shaarli_version.php',
419 if (preg_match('/(\d+)\.\d+$/', $latestVersion, $matches) === false) {
422 $latestMajor = $matches[1];
424 // Get current major version digit
425 preg_match('/(\d+)\.\d+$/', SHAARLI_VERSION
, $matches);
426 $currentMajor = $matches[1];
428 if ($currentMajor === $latestMajor) {
433 $this->conf
->set('updates.check_updates_branch', $branch);
434 $this->conf
->write($this->isLoggedIn
);
439 * Reset history store file due to date format change.
441 public function updateMethodResetHistoryFile()
443 if (is_file($this->conf
->get('resource.history'))) {
444 unlink($this->conf
->get('resource.history'));
450 * Save the datastore -> the link order is now applied when links are saved.
452 public function updateMethodReorderDatastore()
454 $this->linkDB
->save($this->conf
->get('resource.page_cache'));
459 * Change privateonly session key to visibility.
461 public function updateMethodVisibilitySession()
463 if (isset($_SESSION['privateonly'])) {
464 unset($_SESSION['privateonly']);
465 $_SESSION['visibility'] = 'private';
471 * Add download size and timeout to the configuration file
473 * @return bool true if the update is successful, false otherwise.
475 public function updateMethodDownloadSizeAndTimeoutConf()
477 if ($this->conf
->exists('general.download_max_size')
478 && $this->conf
->exists('general.download_timeout')
483 if (! $this->conf
->exists('general.download_max_size')) {
484 $this->conf
->set('general.download_max_size', 1024*1024*4);
487 if (! $this->conf
->exists('general.download_timeout')) {
488 $this->conf
->set('general.download_timeout', 30);
491 $this->conf
->write($this->isLoggedIn
);
496 * * Move thumbnails management to WebThumbnailer, coming with new settings.
498 public function updateMethodWebThumbnailer()
500 if ($this->conf
->exists('thumbnails.enabled')) {
504 $thumbnailsEnabled = $this->conf
->get('thumbnail.enable_thumbnails', true);
505 $this->conf
->set('thumbnails.enabled', $thumbnailsEnabled);
506 $this->conf
->set('thumbnails.width', 125);
507 $this->conf
->set('thumbnails.height', 90);
508 $this->conf
->remove('thumbnail');
509 $this->conf
->write(true);
511 if ($thumbnailsEnabled) {
512 $this->session
['warnings'][] = t(
513 'You have enabled thumbnails. <a href="?do=thumbs_update">Please synchonize them</a>.'
522 * Class UpdaterException.
524 class UpdaterException
extends Exception
527 * @var string Method where the error occurred.
532 * @var Exception The parent exception.
539 * @param string $message Force the error message if set.
540 * @param string $method Method where the error occurred.
541 * @param Exception|bool $previous Parent exception.
543 public function __construct($message = '', $method = '', $previous = false)
545 $this->method
= $method;
546 $this->previous
= $previous;
547 $this->message
= $this->buildMessage($message);
551 * Build the exception error message.
553 * @param string $message Optional given error message.
555 * @return string The built error message.
557 private function buildMessage($message)
560 if (! empty($message)) {
561 $out .= $message . PHP_EOL
;
564 if (! empty($this->method
)) {
565 $out .= t('An error occurred while running the update ') . $this->method
. PHP_EOL
;
568 if (! empty($this->previous
)) {
569 $out .= ' '. $this->previous
->getMessage();
577 * Read the updates file, and return already done updates.
579 * @param string $updatesFilepath Updates file path.
581 * @return array Already done update methods.
583 function read_updates_file($updatesFilepath)
585 if (! empty($updatesFilepath) && is_file($updatesFilepath)) {
586 $content = file_get_contents($updatesFilepath);
587 if (! empty($content)) {
588 return explode(';', $content);
595 * Write updates file.
597 * @param string $updatesFilepath Updates file path.
598 * @param array $updates Updates array to write.
600 * @throws Exception Couldn't write version number.
602 function write_updates_file($updatesFilepath, $updates)
604 if (empty($updatesFilepath)) {
605 throw new Exception(t('Updates file path is not set, can\'t write updates.'));
608 $res = file_put_contents($updatesFilepath, implode(';', $updates));
609 if ($res === false) {
610 throw new Exception(t('Unable to write updates in '. $updatesFilepath . '.'));