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