]> git.immae.eu Git - github/shaarli/Shaarli.git/blame - application/Updater.php
Docker: expose a volume for the thumbnail cache
[github/shaarli/Shaarli.git] / application / Updater.php
CommitLineData
510377d2 1<?php
3c66e564
V
2use Shaarli\Config\ConfigJson;
3use Shaarli\Config\ConfigPhp;
fe83d45c 4use Shaarli\Config\ConfigManager;
510377d2
A
5
6/**
7 * Class Updater.
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.
10 */
11class Updater
12{
13 /**
14 * @var array Updates which are already done.
15 */
16 protected $doneUpdates;
17
510377d2
A
18 /**
19 * @var LinkDB instance.
20 */
21 protected $linkDB;
22
278d9ee2
A
23 /**
24 * @var ConfigManager $conf Configuration Manager instance.
25 */
26 protected $conf;
27
510377d2
A
28 /**
29 * @var bool True if the user is logged in, false otherwise.
30 */
31 protected $isLoggedIn;
32
33 /**
34 * @var ReflectionMethod[] List of current class methods.
35 */
36 protected $methods;
37
38 /**
39 * Object constructor.
40 *
278d9ee2
A
41 * @param array $doneUpdates Updates which are already done.
42 * @param LinkDB $linkDB LinkDB instance.
7af9a418 43 * @param ConfigManager $conf Configuration Manager instance.
278d9ee2 44 * @param boolean $isLoggedIn True if the user is logged in.
510377d2 45 */
278d9ee2 46 public function __construct($doneUpdates, $linkDB, $conf, $isLoggedIn)
510377d2
A
47 {
48 $this->doneUpdates = $doneUpdates;
510377d2 49 $this->linkDB = $linkDB;
278d9ee2 50 $this->conf = $conf;
510377d2
A
51 $this->isLoggedIn = $isLoggedIn;
52
53 // Retrieve all update methods.
54 $class = new ReflectionClass($this);
55 $this->methods = $class->getMethods();
56 }
57
58 /**
59 * Run all new updates.
60 * Update methods have to start with 'updateMethod' and return true (on success).
61 *
62 * @return array An array containing ran updates.
63 *
64 * @throws UpdaterException If something went wrong.
65 */
66 public function update()
67 {
68 $updatesRan = array();
69
70 // If the user isn't logged in, exit without updating.
71 if ($this->isLoggedIn !== true) {
72 return $updatesRan;
73 }
74
ee6f4b64 75 if ($this->methods === null) {
12266213 76 throw new UpdaterException(t('Couldn\'t retrieve Updater class methods.'));
510377d2
A
77 }
78
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)
83 ) {
84 continue;
85 }
86
87 try {
88 $method->setAccessible(true);
89 $res = $method->invoke($this);
90 // Update method must return true to be considered processed.
91 if ($res === true) {
92 $updatesRan[] = $method->getName();
93 }
94 } catch (Exception $e) {
95 throw new UpdaterException($method, $e);
96 }
97 }
98
99 $this->doneUpdates = array_merge($this->doneUpdates, $updatesRan);
100
101 return $updatesRan;
102 }
103
104 /**
105 * @return array Updates methods already processed.
106 */
107 public function getDoneUpdates()
108 {
109 return $this->doneUpdates;
110 }
111
112 /**
113 * Move deprecated options.php to config.php.
114 *
115 * Milestone 0.9 (old versioning) - shaarli/Shaarli#41:
116 * options.php is not supported anymore.
117 */
118 public function updateMethodMergeDeprecatedConfigFile()
119 {
894a3c4b
A
120 if (is_file($this->conf->get('resource.data_dir') . '/options.php')) {
121 include $this->conf->get('resource.data_dir') . '/options.php';
510377d2
A
122
123 // Load GLOBALS into config
684e662a
A
124 $allowedKeys = array_merge(ConfigPhp::$ROOT_KEYS);
125 $allowedKeys[] = 'config';
510377d2 126 foreach ($GLOBALS as $key => $value) {
684e662a 127 if (in_array($key, $allowedKeys)) {
278d9ee2 128 $this->conf->set($key, $value);
684e662a 129 }
510377d2 130 }
278d9ee2 131 $this->conf->write($this->isLoggedIn);
894a3c4b 132 unlink($this->conf->get('resource.data_dir').'/options.php');
510377d2
A
133 }
134
135 return true;
136 }
21979ff1 137
b74b96bf
A
138 /**
139 * Move old configuration in PHP to the new config system in JSON format.
140 *
da10377b
A
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.
b74b96bf
A
143 */
144 public function updateMethodConfigToJson()
145 {
b74b96bf 146 // JSON config already exists, nothing to do.
278d9ee2 147 if ($this->conf->getConfigIO() instanceof ConfigJson) {
b74b96bf
A
148 return true;
149 }
150
151 $configPhp = new ConfigPhp();
152 $configJson = new ConfigJson();
278d9ee2
A
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();
b74b96bf 157
da10377b 158 $legacyMap = array_flip(ConfigPhp::$LEGACY_KEYS_MAPPING);
b74b96bf 159 foreach (ConfigPhp::$ROOT_KEYS as $key) {
278d9ee2 160 $this->conf->set($legacyMap[$key], $oldConfig[$key]);
b74b96bf
A
161 }
162
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) {
da10377b
A
167 if (isset($legacyMap[$sub .'.'. $key])) {
168 $configKey = $legacyMap[$sub .'.'. $key];
169 } else {
170 $configKey = $sub .'.'. $key;
171 }
278d9ee2 172 $this->conf->set($configKey, $value);
b74b96bf
A
173 }
174 }
175
176 try{
278d9ee2 177 $this->conf->write($this->isLoggedIn);
b74b96bf
A
178 return true;
179 } catch (IOException $e) {
180 error_log($e->getMessage());
181 return false;
182 }
183 }
7f179985
A
184
185 /**
186 * Escape settings which have been manually escaped in every request in previous versions:
187 * - general.title
188 * - general.header_link
b9f8b837 189 * - redirector.url
7f179985
A
190 *
191 * @return bool true if the update is successful, false otherwise.
192 */
b9f8b837 193 public function updateMethodEscapeUnescapedConfig()
7f179985 194 {
7f179985 195 try {
278d9ee2
A
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')));
894a3c4b 198 $this->conf->set('redirector.url', escape($this->conf->get('redirector.url')));
278d9ee2 199 $this->conf->write($this->isLoggedIn);
7f179985
A
200 } catch (Exception $e) {
201 error_log($e->getMessage());
202 return false;
203 }
204 return true;
205 }
1dc37f9c
A
206
207 /**
208 * Update the database to use the new ID system, which replaces linkdate primary keys.
01878a75 209 * Also, creation and update dates are now DateTime objects (done by LinkDB).
1dc37f9c
A
210 *
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.
213 *
d592daea
A
214 * LinkDB also adds the field 'shorturl' with the precedent format (linkdate smallhash),
215 * which will be saved by this method.
216 *
1dc37f9c
A
217 * @return bool true if the update is successful, false otherwise.
218 */
219 public function updateMethodDatastoreIds()
220 {
221 // up to date database
222 if (isset($this->linkDB[0])) {
223 return true;
224 }
225
226 $save = $this->conf->get('resource.data_dir') .'/datastore.'. date('YmdHis') .'.php';
227 copy($this->conf->get('resource.datastore'), $save);
228
229 $links = array();
230 foreach ($this->linkDB as $offset => $value) {
231 $links[] = $value;
232 unset($this->linkDB[$offset]);
233 }
234 $links = array_reverse($links);
235 $cpt = 0;
236 foreach ($links as $l) {
1dc37f9c
A
237 unset($l['linkdate']);
238 $l['id'] = $cpt;
239 $this->linkDB[$cpt++] = $l;
240 }
241
242 $this->linkDB->save($this->conf->get('resource.page_cache'));
243 $this->linkDB->reorder();
244
245 return true;
246 }
cbfdcff2 247
c03455af
A
248 /**
249 * Rename tags starting with a '-' to work with tag exclusion search.
250 */
251 public function updateMethodRenameDashTags()
252 {
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;
258 }
259 $this->linkDB->save($this->conf->get('resource.page_cache'));
260 return true;
261 }
262
cbfdcff2
A
263 /**
264 * Initialize API settings:
265 * - api.enabled: true
266 * - api.secret: generated secret
267 */
268 public function updateMethodApiSettings()
269 {
270 if ($this->conf->exists('api.secret')) {
271 return true;
272 }
273
274 $this->conf->set('api.enabled', true);
275 $this->conf->set(
276 'api.secret',
277 generate_api_secret(
278 $this->conf->get('credentials.login'),
279 $this->conf->get('credentials.salt')
280 )
281 );
282 $this->conf->write($this->isLoggedIn);
283 return true;
284 }
04a0e8ea
A
285
286 /**
287 * New setting: theme name. If the default theme is used, nothing to do.
288 *
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.
291 *
292 * @return bool true if the update is successful, false otherwise.
293 */
294 public function updateMethodDefaultTheme()
295 {
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)) {
301 return true;
302 }
303
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);
308
309 // Dependency injection gore
310 RainTPL::$tpl_dir = $tplDir;
311
312 return true;
313 }
7282418b
A
314
315 /**
316 * Move the file to inc/user.css to data/user.css.
317 *
318 * Note: Due to hardcoded paths, it's not unit testable. But one line of code should be fine.
319 *
320 * @return bool true if the update is successful, false otherwise.
321 */
322 public function updateMethodMoveUserCss()
323 {
324 if (! is_file('inc/user.css')) {
325 return true;
326 }
327
328 return rename('inc/user.css', 'data/user.css');
329 }
7dcbfde5 330
e0376101
A
331 /**
332 * * `markdown_escape` is a new setting, set to true as default.
333 *
334 * If the markdown plugin was already enabled, escaping is disabled to avoid
335 * breaking existing entries.
336 */
337 public function updateMethodEscapeMarkdown()
338 {
339 if ($this->conf->exists('security.markdown_escape')) {
340 return true;
341 }
342
343 if (in_array('markdown', $this->conf->get('general.enabled_plugins'))) {
344 $this->conf->set('security.markdown_escape', false);
345 } else {
346 $this->conf->set('security.markdown_escape', true);
347 }
348 $this->conf->write($this->isLoggedIn);
349
7dcbfde5
A
350 return true;
351 }
fe83d45c
A
352
353 /**
354 * Add 'http://' to Piwik URL the setting is set.
355 *
356 * @return bool true if the update is successful, false otherwise.
357 */
358 public function updateMethodPiwikUrl()
359 {
360 if (! $this->conf->exists('plugins.PIWIK_URL') || startsWith($this->conf->get('plugins.PIWIK_URL'), 'http')) {
361 return true;
362 }
363
364 $this->conf->set('plugins.PIWIK_URL', 'http://'. $this->conf->get('plugins.PIWIK_URL'));
365 $this->conf->write($this->isLoggedIn);
2ea89aba
A
366
367 return true;
368 }
369
370 /**
371 * Use ATOM feed as default.
372 */
373 public function updateMethodAtomDefault()
374 {
375 if (!$this->conf->exists('feed.show_atom') || $this->conf->get('feed.show_atom') === true) {
376 return true;
377 }
378
379 $this->conf->set('feed.show_atom', true);
380 $this->conf->write($this->isLoggedIn);
381
fe83d45c
A
382 return true;
383 }
bbc6b844
A
384
385 /**
386 * Update updates.check_updates_branch setting.
387 *
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.
391 *
392 * No update required for the dev version.
393 *
394 * Note: due to hardcoded URL and lack of dependency injection, this is not unit testable.
395 *
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.
398 */
399 public function updateMethodCheckUpdateRemoteBranch()
400 {
b3e1f92e 401 if (SHAARLI_VERSION === 'dev' || $this->conf->get('updates.check_updates_branch') === 'latest') {
bbc6b844
A
402 return true;
403 }
404
405 // Get latest branch major version digit
406 $latestVersion = ApplicationUtils::getLatestGitVersionCode(
407 'https://raw.githubusercontent.com/shaarli/Shaarli/latest/shaarli_version.php',
408 5
409 );
410 if (preg_match('/(\d+)\.\d+$/', $latestVersion, $matches) === false) {
411 return false;
412 }
413 $latestMajor = $matches[1];
414
415 // Get current major version digit
b3e1f92e 416 preg_match('/(\d+)\.\d+$/', SHAARLI_VERSION, $matches);
bbc6b844
A
417 $currentMajor = $matches[1];
418
419 if ($currentMajor === $latestMajor) {
420 $branch = 'latest';
421 } else {
422 $branch = 'stable';
423 }
424 $this->conf->set('updates.check_updates_branch', $branch);
425 $this->conf->write($this->isLoggedIn);
426 return true;
427 }
57ce6dae
A
428
429 /**
430 * Reset history store file due to date format change.
431 */
432 public function updateMethodResetHistoryFile()
433 {
434 if (is_file($this->conf->get('resource.history'))) {
435 unlink($this->conf->get('resource.history'));
436 }
437 return true;
438 }
9ec0a611
A
439
440 /**
441 * Save the datastore -> the link order is now applied when links are saved.
442 */
443 public function updateMethodReorderDatastore()
444 {
445 $this->linkDB->save($this->conf->get('resource.page_cache'));
270da705 446 return true;
9ec0a611 447 }
9d4736a3
A
448
449 /**
450 * Change privateonly session key to visibility.
451 */
452 public function updateMethodVisibilitySession()
453 {
454 if (isset($_SESSION['privateonly'])) {
455 unset($_SESSION['privateonly']);
456 $_SESSION['visibility'] = 'private';
457 }
458 return true;
459 }
4ff3ed1c
A
460
461 /**
462 * Add download size and timeout to the configuration file
463 *
464 * @return bool true if the update is successful, false otherwise.
465 */
466 public function updateMethodDownloadSizeAndTimeoutConf()
467 {
468 if ($this->conf->exists('general.download_max_size')
469 && $this->conf->exists('general.download_timeout')
470 ) {
471 return true;
472 }
473
474 if (! $this->conf->exists('general.download_max_size')) {
475 $this->conf->set('general.download_max_size', 1024*1024*4);
476 }
477
478 if (! $this->conf->exists('general.download_timeout')) {
479 $this->conf->set('general.download_timeout', 30);
480 }
481
482 $this->conf->write($this->isLoggedIn);
483
484 return true;
485 }
510377d2
A
486}
487
488/**
489 * Class UpdaterException.
490 */
491class UpdaterException extends Exception
492{
493 /**
494 * @var string Method where the error occurred.
495 */
496 protected $method;
497
498 /**
499 * @var Exception The parent exception.
500 */
501 protected $previous;
502
503 /**
504 * Constructor.
505 *
506 * @param string $message Force the error message if set.
507 * @param string $method Method where the error occurred.
508 * @param Exception|bool $previous Parent exception.
509 */
510 public function __construct($message = '', $method = '', $previous = false)
511 {
512 $this->method = $method;
513 $this->previous = $previous;
514 $this->message = $this->buildMessage($message);
515 }
516
517 /**
518 * Build the exception error message.
519 *
520 * @param string $message Optional given error message.
521 *
522 * @return string The built error message.
523 */
524 private function buildMessage($message)
525 {
526 $out = '';
527 if (! empty($message)) {
528 $out .= $message . PHP_EOL;
529 }
530
531 if (! empty($this->method)) {
12266213 532 $out .= t('An error occurred while running the update ') . $this->method . PHP_EOL;
510377d2
A
533 }
534
535 if (! empty($this->previous)) {
536 $out .= ' '. $this->previous->getMessage();
537 }
538
539 return $out;
540 }
541}
542
510377d2
A
543/**
544 * Read the updates file, and return already done updates.
545 *
546 * @param string $updatesFilepath Updates file path.
547 *
548 * @return array Already done update methods.
549 */
550function read_updates_file($updatesFilepath)
551{
552 if (! empty($updatesFilepath) && is_file($updatesFilepath)) {
553 $content = file_get_contents($updatesFilepath);
554 if (! empty($content)) {
555 return explode(';', $content);
556 }
557 }
558 return array();
559}
560
561/**
562 * Write updates file.
563 *
564 * @param string $updatesFilepath Updates file path.
565 * @param array $updates Updates array to write.
566 *
567 * @throws Exception Couldn't write version number.
568 */
569function write_updates_file($updatesFilepath, $updates)
570{
571 if (empty($updatesFilepath)) {
12266213 572 throw new Exception(t('Updates file path is not set, can\'t write updates.'));
510377d2
A
573 }
574
575 $res = file_put_contents($updatesFilepath, implode(';', $updates));
576 if ($res === false) {
12266213 577 throw new Exception(t('Unable to write updates in '. $updatesFilepath . '.'));
510377d2
A
578 }
579}