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