aboutsummaryrefslogtreecommitdiffhomepage
path: root/application/Updater.php
diff options
context:
space:
mode:
authorArthurHoaro <arthur@hoa.ro>2020-10-13 12:07:13 +0200
committerArthurHoaro <arthur@hoa.ro>2020-10-13 12:07:13 +0200
commitd9f6275ebca035fec8331652c677981056793ccc (patch)
tree37a64baf4f0eba6b781040605965383d8aded2cc /application/Updater.php
parent38672ba0d1c722e5d6d33a58255ceb55e9410e46 (diff)
parentd63ff87a009313141ae684ec447b902562ff6ee7 (diff)
downloadShaarli-stable.tar.gz
Shaarli-stable.tar.zst
Shaarli-stable.zip
Merge branch 'v0.11' into stablestable
Diffstat (limited to 'application/Updater.php')
-rw-r--r--application/Updater.php635
1 files changed, 0 insertions, 635 deletions
diff --git a/application/Updater.php b/application/Updater.php
deleted file mode 100644
index 86a21fc3..00000000
--- a/application/Updater.php
+++ /dev/null
@@ -1,635 +0,0 @@
1<?php
2use Shaarli\Config\ConfigJson;
3use Shaarli\Config\ConfigPhp;
4use Shaarli\Config\ConfigManager;
5use Shaarli\Thumbnailer;
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
19 /**
20 * @var LinkDB instance.
21 */
22 protected $linkDB;
23
24 /**
25 * @var ConfigManager $conf Configuration Manager instance.
26 */
27 protected $conf;
28
29 /**
30 * @var bool True if the user is logged in, false otherwise.
31 */
32 protected $isLoggedIn;
33
34 /**
35 * @var array $_SESSION
36 */
37 protected $session;
38
39 /**
40 * @var ReflectionMethod[] List of current class methods.
41 */
42 protected $methods;
43
44 /**
45 * Object constructor.
46 *
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)
52 *
53 * @throws ReflectionException
54 */
55 public function __construct($doneUpdates, $linkDB, $conf, $isLoggedIn, &$session = [])
56 {
57 $this->doneUpdates = $doneUpdates;
58 $this->linkDB = $linkDB;
59 $this->conf = $conf;
60 $this->isLoggedIn = $isLoggedIn;
61 $this->session = &$session;
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
85 if ($this->methods === null) {
86 throw new UpdaterException(t('Couldn\'t retrieve Updater class methods.'));
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 {
130 if (is_file($this->conf->get('resource.data_dir') . '/options.php')) {
131 include $this->conf->get('resource.data_dir') . '/options.php';
132
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);
139 }
140 }
141 $this->conf->write($this->isLoggedIn);
142 unlink($this->conf->get('resource.data_dir').'/options.php');
143 }
144
145 return true;
146 }
147
148 /**
149 * Move old configuration in PHP to the new config system in JSON format.
150 *
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.
153 */
154 public function updateMethodConfigToJson()
155 {
156 // JSON config already exists, nothing to do.
157 if ($this->conf->getConfigIO() instanceof ConfigJson) {
158 return true;
159 }
160
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();
167
168 $legacyMap = array_flip(ConfigPhp::$LEGACY_KEYS_MAPPING);
169 foreach (ConfigPhp::$ROOT_KEYS as $key) {
170 $this->conf->set($legacyMap[$key], $oldConfig[$key]);
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) {
177 if (isset($legacyMap[$sub .'.'. $key])) {
178 $configKey = $legacyMap[$sub .'.'. $key];
179 } else {
180 $configKey = $sub .'.'. $key;
181 }
182 $this->conf->set($configKey, $value);
183 }
184 }
185
186 try {
187 $this->conf->write($this->isLoggedIn);
188 return true;
189 } catch (IOException $e) {
190 error_log($e->getMessage());
191 return false;
192 }
193 }
194
195 /**
196 * Escape settings which have been manually escaped in every request in previous versions:
197 * - general.title
198 * - general.header_link
199 * - redirector.url
200 *
201 * @return bool true if the update is successful, false otherwise.
202 */
203 public function updateMethodEscapeUnescapedConfig()
204 {
205 try {
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());
212 return false;
213 }
214 return true;
215 }
216
217 /**
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).
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 *
224 * LinkDB also adds the field 'shorturl' with the precedent format (linkdate smallhash),
225 * which will be saved by this method.
226 *
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) {
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 }
257
258 /**
259<<<<<<< HEAD
260=======
261 * Rename tags starting with a '-' to work with tag exclusion search.
262 */
263 public function updateMethodRenameDashTags()
264 {
265 $linklist = $this->linkDB->filterSearch();
266 foreach ($linklist as $key => $link) {
267 $link['tags'] = preg_replace('/(^| )\-/', '$1', $link['tags']);
268 $link['tags'] = implode(' ', array_unique(LinkFilter::tagsStrToArray($link['tags'], true)));
269 $this->linkDB[$key] = $link;
270 }
271 $this->linkDB->save($this->conf->get('resource.page_cache'));
272 return true;
273 }
274
275 /**
276 * Initialize API settings:
277 * - api.enabled: true
278 * - api.secret: generated secret
279 */
280 public function updateMethodApiSettings()
281 {
282 if ($this->conf->exists('api.secret')) {
283 return true;
284 }
285
286 $this->conf->set('api.enabled', true);
287 $this->conf->set(
288 'api.secret',
289 generate_api_secret(
290 $this->conf->get('credentials.login'),
291 $this->conf->get('credentials.salt')
292 )
293 );
294 $this->conf->write($this->isLoggedIn);
295 return true;
296 }
297
298 /**
299 * New setting: theme name. If the default theme is used, nothing to do.
300 *
301 * If the user uses a custom theme, raintpl_tpl dir is updated to the parent directory,
302 * and the current theme is set as default in the theme setting.
303 *
304 * @return bool true if the update is successful, false otherwise.
305 */
306 public function updateMethodDefaultTheme()
307 {
308 // raintpl_tpl isn't the root template directory anymore.
309 // We run the update only if this folder still contains the template files.
310 $tplDir = $this->conf->get('resource.raintpl_tpl');
311 $tplFile = $tplDir . '/linklist.html';
312 if (! file_exists($tplFile)) {
313 return true;
314 }
315
316 $parent = dirname($tplDir);
317 $this->conf->set('resource.raintpl_tpl', $parent);
318 $this->conf->set('resource.theme', trim(str_replace($parent, '', $tplDir), '/'));
319 $this->conf->write($this->isLoggedIn);
320
321 // Dependency injection gore
322 RainTPL::$tpl_dir = $tplDir;
323
324 return true;
325 }
326
327 /**
328 * Move the file to inc/user.css to data/user.css.
329 *
330 * Note: Due to hardcoded paths, it's not unit testable. But one line of code should be fine.
331 *
332 * @return bool true if the update is successful, false otherwise.
333 */
334 public function updateMethodMoveUserCss()
335 {
336 if (! is_file('inc/user.css')) {
337 return true;
338 }
339
340 return rename('inc/user.css', 'data/user.css');
341 }
342
343 /**
344 * * `markdown_escape` is a new setting, set to true as default.
345 *
346 * If the markdown plugin was already enabled, escaping is disabled to avoid
347 * breaking existing entries.
348 */
349 public function updateMethodEscapeMarkdown()
350 {
351 if ($this->conf->exists('security.markdown_escape')) {
352 return true;
353 }
354
355 if (in_array('markdown', $this->conf->get('general.enabled_plugins'))) {
356 $this->conf->set('security.markdown_escape', false);
357 } else {
358 $this->conf->set('security.markdown_escape', true);
359 }
360 $this->conf->write($this->isLoggedIn);
361
362 return true;
363 }
364
365 /**
366 * Add 'http://' to Piwik URL the setting is set.
367 *
368 * @return bool true if the update is successful, false otherwise.
369 */
370 public function updateMethodPiwikUrl()
371 {
372 if (! $this->conf->exists('plugins.PIWIK_URL') || startsWith($this->conf->get('plugins.PIWIK_URL'), 'http')) {
373 return true;
374 }
375
376 $this->conf->set('plugins.PIWIK_URL', 'http://'. $this->conf->get('plugins.PIWIK_URL'));
377 $this->conf->write($this->isLoggedIn);
378
379 return true;
380 }
381
382 /**
383 * Use ATOM feed as default.
384 */
385 public function updateMethodAtomDefault()
386 {
387 if (!$this->conf->exists('feed.show_atom') || $this->conf->get('feed.show_atom') === true) {
388 return true;
389 }
390
391 $this->conf->set('feed.show_atom', true);
392 $this->conf->write($this->isLoggedIn);
393
394 return true;
395 }
396
397 /**
398 * Update updates.check_updates_branch setting.
399 *
400 * If the current major version digit matches the latest branch
401 * major version digit, we set the branch to `latest`,
402 * otherwise we'll check updates on the `stable` branch.
403 *
404 * No update required for the dev version.
405 *
406 * Note: due to hardcoded URL and lack of dependency injection, this is not unit testable.
407 *
408 * FIXME! This needs to be removed when we switch to first digit major version
409 * instead of the second one since the versionning process will change.
410 */
411 public function updateMethodCheckUpdateRemoteBranch()
412 {
413 if (SHAARLI_VERSION === 'dev' || $this->conf->get('updates.check_updates_branch') === 'latest') {
414 return true;
415 }
416
417 // Get latest branch major version digit
418 $latestVersion = ApplicationUtils::getLatestGitVersionCode(
419 'https://raw.githubusercontent.com/shaarli/Shaarli/latest/shaarli_version.php',
420 5
421 );
422 if (preg_match('/(\d+)\.\d+$/', $latestVersion, $matches) === false) {
423 return false;
424 }
425 $latestMajor = $matches[1];
426
427 // Get current major version digit
428 preg_match('/(\d+)\.\d+$/', SHAARLI_VERSION, $matches);
429 $currentMajor = $matches[1];
430
431 if ($currentMajor === $latestMajor) {
432 $branch = 'latest';
433 } else {
434 $branch = 'stable';
435 }
436 $this->conf->set('updates.check_updates_branch', $branch);
437 $this->conf->write($this->isLoggedIn);
438 return true;
439 }
440
441 /**
442 * Reset history store file due to date format change.
443 */
444 public function updateMethodResetHistoryFile()
445 {
446 if (is_file($this->conf->get('resource.history'))) {
447 unlink($this->conf->get('resource.history'));
448 }
449 return true;
450 }
451
452 /**
453 * Save the datastore -> the link order is now applied when links are saved.
454 */
455 public function updateMethodReorderDatastore()
456 {
457 $this->linkDB->save($this->conf->get('resource.page_cache'));
458 return true;
459 }
460
461 /**
462 * Change privateonly session key to visibility.
463 */
464 public function updateMethodVisibilitySession()
465 {
466 if (isset($_SESSION['privateonly'])) {
467 unset($_SESSION['privateonly']);
468 $_SESSION['visibility'] = 'private';
469 }
470 return true;
471 }
472
473 /**
474 * Add download size and timeout to the configuration file
475 *
476 * @return bool true if the update is successful, false otherwise.
477 */
478 public function updateMethodDownloadSizeAndTimeoutConf()
479 {
480 if ($this->conf->exists('general.download_max_size')
481 && $this->conf->exists('general.download_timeout')
482 ) {
483 return true;
484 }
485
486 if (! $this->conf->exists('general.download_max_size')) {
487 $this->conf->set('general.download_max_size', 1024*1024*4);
488 }
489
490 if (! $this->conf->exists('general.download_timeout')) {
491 $this->conf->set('general.download_timeout', 30);
492 }
493
494 $this->conf->write($this->isLoggedIn);
495 return true;
496 }
497
498 /**
499 * * Move thumbnails management to WebThumbnailer, coming with new settings.
500 */
501 public function updateMethodWebThumbnailer()
502 {
503 if ($this->conf->exists('thumbnails.mode')) {
504 return true;
505 }
506
507 $thumbnailsEnabled = extension_loaded('gd') && $this->conf->get('thumbnail.enable_thumbnails', true);
508 $this->conf->set('thumbnails.mode', $thumbnailsEnabled ? Thumbnailer::MODE_ALL : Thumbnailer::MODE_NONE);
509 $this->conf->set('thumbnails.width', 125);
510 $this->conf->set('thumbnails.height', 90);
511 $this->conf->remove('thumbnail');
512 $this->conf->write(true);
513
514 if ($thumbnailsEnabled) {
515 $this->session['warnings'][] = t(
516 'You have enabled or changed thumbnails mode. <a href="?do=thumbs_update">Please synchronize them</a>.'
517 );
518 }
519
520 return true;
521 }
522
523 /**
524 * Set sticky = false on all links
525 *
526 * @return bool true if the update is successful, false otherwise.
527 */
528 public function updateMethodSetSticky()
529 {
530 foreach ($this->linkDB as $key => $link) {
531 if (isset($link['sticky'])) {
532 return true;
533 }
534 $link['sticky'] = false;
535 $this->linkDB[$key] = $link;
536 }
537
538 $this->linkDB->save($this->conf->get('resource.page_cache'));
539
540 return true;
541 }
542}
543
544/**
545 * Class UpdaterException.
546 */
547class UpdaterException extends Exception
548{
549 /**
550 * @var string Method where the error occurred.
551 */
552 protected $method;
553
554 /**
555 * @var Exception The parent exception.
556 */
557 protected $previous;
558
559 /**
560 * Constructor.
561 *
562 * @param string $message Force the error message if set.
563 * @param string $method Method where the error occurred.
564 * @param Exception|bool $previous Parent exception.
565 */
566 public function __construct($message = '', $method = '', $previous = false)
567 {
568 $this->method = $method;
569 $this->previous = $previous;
570 $this->message = $this->buildMessage($message);
571 }
572
573 /**
574 * Build the exception error message.
575 *
576 * @param string $message Optional given error message.
577 *
578 * @return string The built error message.
579 */
580 private function buildMessage($message)
581 {
582 $out = '';
583 if (! empty($message)) {
584 $out .= $message . PHP_EOL;
585 }
586
587 if (! empty($this->method)) {
588 $out .= t('An error occurred while running the update ') . $this->method . PHP_EOL;
589 }
590
591 if (! empty($this->previous)) {
592 $out .= ' '. $this->previous->getMessage();
593 }
594
595 return $out;
596 }
597}
598
599/**
600 * Read the updates file, and return already done updates.
601 *
602 * @param string $updatesFilepath Updates file path.
603 *
604 * @return array Already done update methods.
605 */
606function read_updates_file($updatesFilepath)
607{
608 if (! empty($updatesFilepath) && is_file($updatesFilepath)) {
609 $content = file_get_contents($updatesFilepath);
610 if (! empty($content)) {
611 return explode(';', $content);
612 }
613 }
614 return array();
615}
616
617/**
618 * Write updates file.
619 *
620 * @param string $updatesFilepath Updates file path.
621 * @param array $updates Updates array to write.
622 *
623 * @throws Exception Couldn't write version number.
624 */
625function write_updates_file($updatesFilepath, $updates)
626{
627 if (empty($updatesFilepath)) {
628 throw new Exception(t('Updates file path is not set, can\'t write updates.'));
629 }
630
631 $res = file_put_contents($updatesFilepath, implode(';', $updates));
632 if ($res === false) {
633 throw new Exception(t('Unable to write updates in '. $updatesFilepath . '.'));
634 }
635}