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