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