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