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 ReflectionMethod[] List of current class methods.
41 * @param array $doneUpdates Updates which are already done.
42 * @param LinkDB $linkDB LinkDB instance.
43 * @param ConfigManager $conf Configuration Manager instance.
44 * @param boolean $isLoggedIn True if the user is logged in.
46 public function __construct($doneUpdates, $linkDB, $conf, $isLoggedIn)
48 $this->doneUpdates
= $doneUpdates;
49 $this->linkDB
= $linkDB;
51 $this->isLoggedIn
= $isLoggedIn;
53 // Retrieve all update methods.
54 $class = new ReflectionClass($this);
55 $this->methods
= $class->getMethods();
59 * Run all new updates.
60 * Update methods have to start with 'updateMethod' and return true (on success).
62 * @return array An array containing ran updates.
64 * @throws UpdaterException If something went wrong.
66 public function update()
68 $updatesRan = array();
70 // If the user isn't logged in, exit without updating.
71 if ($this->isLoggedIn
!== true) {
75 if ($this->methods
=== null) {
76 throw new UpdaterException('Couldn\'t retrieve Updater class methods.');
79 foreach ($this->methods
as $method) {
80 // Not an update method or already done, pass.
81 if (! startsWith($method->getName(), 'updateMethod')
82 || in_array($method->getName(), $this->doneUpdates
)
88 $method->setAccessible(true);
89 $res = $method->invoke($this);
90 // Update method must return true to be considered processed.
92 $updatesRan[] = $method->getName();
94 } catch (Exception
$e) {
95 throw new UpdaterException($method, $e);
99 $this->doneUpdates
= array_merge($this->doneUpdates
, $updatesRan);
105 * @return array Updates methods already processed.
107 public function getDoneUpdates()
109 return $this->doneUpdates
;
113 * Move deprecated options.php to config.php.
115 * Milestone 0.9 (old versioning) - shaarli/Shaarli#41:
116 * options.php is not supported anymore.
118 public function updateMethodMergeDeprecatedConfigFile()
120 if (is_file($this->conf
->get('resource.data_dir') . '/options.php')) {
121 include $this->conf
->get('resource.data_dir') . '/options.php';
123 // Load GLOBALS into config
124 $allowedKeys = array_merge(ConfigPhp
::$ROOT_KEYS);
125 $allowedKeys[] = 'config';
126 foreach ($GLOBALS as $key => $value) {
127 if (in_array($key, $allowedKeys)) {
128 $this->conf
->set($key, $value);
131 $this->conf
->write($this->isLoggedIn
);
132 unlink($this->conf
->get('resource.data_dir').'/options.php');
139 * Move old configuration in PHP to the new config system in JSON format.
141 * Will rename 'config.php' into 'config.save.php' and create 'config.json.php'.
142 * It will also convert legacy setting keys to the new ones.
144 public function updateMethodConfigToJson()
146 // JSON config already exists, nothing to do.
147 if ($this->conf
->getConfigIO() instanceof ConfigJson
) {
151 $configPhp = new ConfigPhp();
152 $configJson = new ConfigJson();
153 $oldConfig = $configPhp->read($this->conf
->getConfigFile() . '.php');
154 rename($this->conf
->getConfigFileExt(), $this->conf
->getConfigFile() . '.save.php');
155 $this->conf
->setConfigIO($configJson);
156 $this->conf
->reload();
158 $legacyMap = array_flip(ConfigPhp
::$LEGACY_KEYS_MAPPING);
159 foreach (ConfigPhp
::$ROOT_KEYS as $key) {
160 $this->conf
->set($legacyMap[$key], $oldConfig[$key]);
163 // Set sub config keys (config and plugins)
164 $subConfig = array('config', 'plugins');
165 foreach ($subConfig as $sub) {
166 foreach ($oldConfig[$sub] as $key => $value) {
167 if (isset($legacyMap[$sub .'.'. $key])) {
168 $configKey = $legacyMap[$sub .'.'. $key];
170 $configKey = $sub .'.'. $key;
172 $this->conf
->set($configKey, $value);
177 $this->conf
->write($this->isLoggedIn
);
179 } catch (IOException
$e) {
180 error_log($e->getMessage());
186 * Escape settings which have been manually escaped in every request in previous versions:
188 * - general.header_link
191 * @return bool true if the update is successful, false otherwise.
193 public function updateMethodEscapeUnescapedConfig()
196 $this->conf
->set('general.title', escape($this->conf
->get('general.title')));
197 $this->conf
->set('general.header_link', escape($this->conf
->get('general.header_link')));
198 $this->conf
->set('redirector.url', escape($this->conf
->get('redirector.url')));
199 $this->conf
->write($this->isLoggedIn
);
200 } catch (Exception
$e) {
201 error_log($e->getMessage());
208 * Update the database to use the new ID system, which replaces linkdate primary keys.
209 * Also, creation and update dates are now DateTime objects (done by LinkDB).
211 * Since this update is very sensitve (changing the whole database), the datastore will be
212 * automatically backed up into the file datastore.<datetime>.php.
214 * LinkDB also adds the field 'shorturl' with the precedent format (linkdate smallhash),
215 * which will be saved by this method.
217 * @return bool true if the update is successful, false otherwise.
219 public function updateMethodDatastoreIds()
221 // up to date database
222 if (isset($this->linkDB
[0])) {
226 $save = $this->conf
->get('resource.data_dir') .'/datastore.'. date('YmdHis') .'.php';
227 copy($this->conf
->get('resource.datastore'), $save);
230 foreach ($this->linkDB
as $offset => $value) {
232 unset($this->linkDB
[$offset]);
234 $links = array_reverse($links);
236 foreach ($links as $l) {
237 unset($l['linkdate']);
239 $this->linkDB
[$cpt++
] = $l;
242 $this->linkDB
->save($this->conf
->get('resource.page_cache'));
243 $this->linkDB
->reorder();
249 * Rename tags starting with a '-' to work with tag exclusion search.
251 public function updateMethodRenameDashTags()
253 $linklist = $this->linkDB
->filterSearch();
254 foreach ($linklist as $key => $link) {
255 $link['tags'] = preg_replace('/(^| )\-/', '$1', $link['tags
']);
256 $link['tags
'] = implode(' ', array_unique(LinkFilter::tagsStrToArray($link['tags
'], true)));
257 $this->linkDB[$key] = $link;
259 $this->linkDB->save($this->conf->get('resource.page_cache
'));
264 * Initialize API settings:
265 * - api.enabled: true
266 * - api.secret: generated secret
268 public function updateMethodApiSettings()
270 if ($this->conf->exists('api
.secret
')) {
274 $this->conf->set('api
.enabled
', true);
278 $this->conf->get('credentials
.login
'),
279 $this->conf->get('credentials
.salt
')
282 $this->conf->write($this->isLoggedIn);
287 * New setting: theme name. If the default theme is used, nothing to do.
289 * If the user uses a custom theme, raintpl_tpl dir is updated to the parent directory,
290 * and the current theme is set as default in the theme setting.
292 * @return bool true if the update is successful, false otherwise.
294 public function updateMethodDefaultTheme()
296 // raintpl_tpl isn't the root template directory anymore
.
297 // We run the update only if this folder still contains the template files.
298 $tplDir = $this->conf
->get('resource.raintpl_tpl');
299 $tplFile = $tplDir . '/linklist.html';
300 if (! file_exists($tplFile)) {
304 $parent = dirname($tplDir);
305 $this->conf
->set('resource.raintpl_tpl', $parent);
306 $this->conf
->set('resource.theme', trim(str_replace($parent, '', $tplDir), '/'));
307 $this->conf
->write($this->isLoggedIn
);
309 // Dependency injection gore
310 RainTPL
::$tpl_dir = $tplDir;
316 * Move the file to inc/user.css to data/user.css.
318 * Note: Due to hardcoded paths, it's not unit testable. But one line of code should be fine.
320 * @return bool true if the update is successful, false otherwise.
322 public function updateMethodMoveUserCss()
324 if (! is_file('inc/user.css')) {
328 return rename('inc/user.css', 'data/user.css');
332 * * `markdown_escape` is a new setting, set to true as default.
334 * If the markdown plugin was already enabled, escaping is disabled to avoid
335 * breaking existing entries.
337 public function updateMethodEscapeMarkdown()
339 if ($this->conf
->exists('security.markdown_escape')) {
343 if (in_array('markdown', $this->conf
->get('general.enabled_plugins'))) {
344 $this->conf
->set('security.markdown_escape', false);
346 $this->conf
->set('security.markdown_escape', true);
348 $this->conf
->write($this->isLoggedIn
);
354 * Add 'http://' to Piwik URL the setting is set.
356 * @return bool true if the update is successful, false otherwise.
358 public function updateMethodPiwikUrl()
360 if (! $this->conf
->exists('plugins.PIWIK_URL') || startsWith($this->conf
->get('plugins.PIWIK_URL'), 'http')) {
364 $this->conf
->set('plugins.PIWIK_URL', 'http://'. $this->conf
->get('plugins.PIWIK_URL'));
365 $this->conf
->write($this->isLoggedIn
);
371 * Use ATOM feed as default.
373 public function updateMethodAtomDefault()
375 if (!$this->conf
->exists('feed.show_atom') || $this->conf
->get('feed.show_atom') === true) {
379 $this->conf
->set('feed.show_atom', true);
380 $this->conf
->write($this->isLoggedIn
);
386 * Update updates.check_updates_branch setting.
388 * If the current major version digit matches the latest branch
389 * major version digit, we set the branch to `latest`,
390 * otherwise we'll check updates on the `stable` branch.
392 * No update required for the dev version.
394 * Note: due to hardcoded URL and lack of dependency injection, this is not unit testable.
396 * FIXME! This needs to be removed when we switch to first digit major version
397 * instead of the second one since the versionning process will change.
399 public function updateMethodCheckUpdateRemoteBranch()
401 if (SHAARLI_VERSION
=== 'dev' || $this->conf
->get('updates.check_updates_branch') === 'latest') {
405 // Get latest branch major version digit
406 $latestVersion = ApplicationUtils
::getLatestGitVersionCode(
407 'https://raw.githubusercontent.com/shaarli/Shaarli/latest/shaarli_version.php',
410 if (preg_match('/(\d+)\.\d+$/', $latestVersion, $matches) === false) {
413 $latestMajor = $matches[1];
415 // Get current major version digit
416 preg_match('/(\d+)\.\d+$/', SHAARLI_VERSION
, $matches);
417 $currentMajor = $matches[1];
419 if ($currentMajor === $latestMajor) {
424 $this->conf
->set('updates.check_updates_branch', $branch);
425 $this->conf
->write($this->isLoggedIn
);
430 * Reset history store file due to date format change.
432 public function updateMethodResetHistoryFile()
434 if (is_file($this->conf
->get('resource.history'))) {
435 unlink($this->conf
->get('resource.history'));
442 * Class UpdaterException.
444 class UpdaterException
extends Exception
447 * @var string Method where the error occurred.
452 * @var Exception The parent exception.
459 * @param string $message Force the error message if set.
460 * @param string $method Method where the error occurred.
461 * @param Exception|bool $previous Parent exception.
463 public function __construct($message = '', $method = '', $previous = false)
465 $this->method
= $method;
466 $this->previous
= $previous;
467 $this->message
= $this->buildMessage($message);
471 * Build the exception error message.
473 * @param string $message Optional given error message.
475 * @return string The built error message.
477 private function buildMessage($message)
480 if (! empty($message)) {
481 $out .= $message . PHP_EOL
;
484 if (! empty($this->method
)) {
485 $out .= 'An error occurred while running the update '. $this->method
. PHP_EOL
;
488 if (! empty($this->previous
)) {
489 $out .= ' '. $this->previous
->getMessage();
497 * Read the updates file, and return already done updates.
499 * @param string $updatesFilepath Updates file path.
501 * @return array Already done update methods.
503 function read_updates_file($updatesFilepath)
505 if (! empty($updatesFilepath) && is_file($updatesFilepath)) {
506 $content = file_get_contents($updatesFilepath);
507 if (! empty($content)) {
508 return explode(';', $content);
515 * Write updates file.
517 * @param string $updatesFilepath Updates file path.
518 * @param array $updates Updates array to write.
520 * @throws Exception Couldn't write version number.
522 function write_updates_file($updatesFilepath, $updates)
524 if (empty($updatesFilepath)) {
525 throw new Exception('Updates file path is not set, can\'t write updates.');
528 $res = file_put_contents($updatesFilepath, implode(';', $updates));
529 if ($res === false) {
530 throw new Exception('Unable to write updates in '. $updatesFilepath . '.');