]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/Updater.php
application: introduce the Shaarli\Config namespace
[github/shaarli/Shaarli.git] / application / Updater.php
1 <?php
2 use Shaarli\Config\ConfigJson;
3 use Shaarli\Config\ConfigPhp;
4
5 /**
6 * Class Updater.
7 * Used to update stuff when a new Shaarli's version is reached.
8 * Update methods are ran only once, and the stored in a JSON file.
9 */
10 class Updater
11 {
12 /**
13 * @var array Updates which are already done.
14 */
15 protected $doneUpdates;
16
17 /**
18 * @var LinkDB instance.
19 */
20 protected $linkDB;
21
22 /**
23 * @var ConfigManager $conf Configuration Manager instance.
24 */
25 protected $conf;
26
27 /**
28 * @var bool True if the user is logged in, false otherwise.
29 */
30 protected $isLoggedIn;
31
32 /**
33 * @var ReflectionMethod[] List of current class methods.
34 */
35 protected $methods;
36
37 /**
38 * Object constructor.
39 *
40 * @param array $doneUpdates Updates which are already done.
41 * @param LinkDB $linkDB LinkDB instance.
42 * @param ConfigManager $conf Configuration Manager instance.
43 * @param boolean $isLoggedIn True if the user is logged in.
44 */
45 public function __construct($doneUpdates, $linkDB, $conf, $isLoggedIn)
46 {
47 $this->doneUpdates = $doneUpdates;
48 $this->linkDB = $linkDB;
49 $this->conf = $conf;
50 $this->isLoggedIn = $isLoggedIn;
51
52 // Retrieve all update methods.
53 $class = new ReflectionClass($this);
54 $this->methods = $class->getMethods();
55 }
56
57 /**
58 * Run all new updates.
59 * Update methods have to start with 'updateMethod' and return true (on success).
60 *
61 * @return array An array containing ran updates.
62 *
63 * @throws UpdaterException If something went wrong.
64 */
65 public function update()
66 {
67 $updatesRan = array();
68
69 // If the user isn't logged in, exit without updating.
70 if ($this->isLoggedIn !== true) {
71 return $updatesRan;
72 }
73
74 if ($this->methods === null) {
75 throw new UpdaterException('Couldn\'t retrieve Updater class methods.');
76 }
77
78 foreach ($this->methods as $method) {
79 // Not an update method or already done, pass.
80 if (! startsWith($method->getName(), 'updateMethod')
81 || in_array($method->getName(), $this->doneUpdates)
82 ) {
83 continue;
84 }
85
86 try {
87 $method->setAccessible(true);
88 $res = $method->invoke($this);
89 // Update method must return true to be considered processed.
90 if ($res === true) {
91 $updatesRan[] = $method->getName();
92 }
93 } catch (Exception $e) {
94 throw new UpdaterException($method, $e);
95 }
96 }
97
98 $this->doneUpdates = array_merge($this->doneUpdates, $updatesRan);
99
100 return $updatesRan;
101 }
102
103 /**
104 * @return array Updates methods already processed.
105 */
106 public function getDoneUpdates()
107 {
108 return $this->doneUpdates;
109 }
110
111 /**
112 * Move deprecated options.php to config.php.
113 *
114 * Milestone 0.9 (old versioning) - shaarli/Shaarli#41:
115 * options.php is not supported anymore.
116 */
117 public function updateMethodMergeDeprecatedConfigFile()
118 {
119 if (is_file($this->conf->get('resource.data_dir') . '/options.php')) {
120 include $this->conf->get('resource.data_dir') . '/options.php';
121
122 // Load GLOBALS into config
123 $allowedKeys = array_merge(ConfigPhp::$ROOT_KEYS);
124 $allowedKeys[] = 'config';
125 foreach ($GLOBALS as $key => $value) {
126 if (in_array($key, $allowedKeys)) {
127 $this->conf->set($key, $value);
128 }
129 }
130 $this->conf->write($this->isLoggedIn);
131 unlink($this->conf->get('resource.data_dir').'/options.php');
132 }
133
134 return true;
135 }
136
137 /**
138 * Move old configuration in PHP to the new config system in JSON format.
139 *
140 * Will rename 'config.php' into 'config.save.php' and create 'config.json.php'.
141 * It will also convert legacy setting keys to the new ones.
142 */
143 public function updateMethodConfigToJson()
144 {
145 // JSON config already exists, nothing to do.
146 if ($this->conf->getConfigIO() instanceof ConfigJson) {
147 return true;
148 }
149
150 $configPhp = new ConfigPhp();
151 $configJson = new ConfigJson();
152 $oldConfig = $configPhp->read($this->conf->getConfigFile() . '.php');
153 rename($this->conf->getConfigFileExt(), $this->conf->getConfigFile() . '.save.php');
154 $this->conf->setConfigIO($configJson);
155 $this->conf->reload();
156
157 $legacyMap = array_flip(ConfigPhp::$LEGACY_KEYS_MAPPING);
158 foreach (ConfigPhp::$ROOT_KEYS as $key) {
159 $this->conf->set($legacyMap[$key], $oldConfig[$key]);
160 }
161
162 // Set sub config keys (config and plugins)
163 $subConfig = array('config', 'plugins');
164 foreach ($subConfig as $sub) {
165 foreach ($oldConfig[$sub] as $key => $value) {
166 if (isset($legacyMap[$sub .'.'. $key])) {
167 $configKey = $legacyMap[$sub .'.'. $key];
168 } else {
169 $configKey = $sub .'.'. $key;
170 }
171 $this->conf->set($configKey, $value);
172 }
173 }
174
175 try{
176 $this->conf->write($this->isLoggedIn);
177 return true;
178 } catch (IOException $e) {
179 error_log($e->getMessage());
180 return false;
181 }
182 }
183
184 /**
185 * Escape settings which have been manually escaped in every request in previous versions:
186 * - general.title
187 * - general.header_link
188 * - redirector.url
189 *
190 * @return bool true if the update is successful, false otherwise.
191 */
192 public function updateMethodEscapeUnescapedConfig()
193 {
194 try {
195 $this->conf->set('general.title', escape($this->conf->get('general.title')));
196 $this->conf->set('general.header_link', escape($this->conf->get('general.header_link')));
197 $this->conf->set('redirector.url', escape($this->conf->get('redirector.url')));
198 $this->conf->write($this->isLoggedIn);
199 } catch (Exception $e) {
200 error_log($e->getMessage());
201 return false;
202 }
203 return true;
204 }
205
206 /**
207 * Update the database to use the new ID system, which replaces linkdate primary keys.
208 * Also, creation and update dates are now DateTime objects (done by LinkDB).
209 *
210 * Since this update is very sensitve (changing the whole database), the datastore will be
211 * automatically backed up into the file datastore.<datetime>.php.
212 *
213 * LinkDB also adds the field 'shorturl' with the precedent format (linkdate smallhash),
214 * which will be saved by this method.
215 *
216 * @return bool true if the update is successful, false otherwise.
217 */
218 public function updateMethodDatastoreIds()
219 {
220 // up to date database
221 if (isset($this->linkDB[0])) {
222 return true;
223 }
224
225 $save = $this->conf->get('resource.data_dir') .'/datastore.'. date('YmdHis') .'.php';
226 copy($this->conf->get('resource.datastore'), $save);
227
228 $links = array();
229 foreach ($this->linkDB as $offset => $value) {
230 $links[] = $value;
231 unset($this->linkDB[$offset]);
232 }
233 $links = array_reverse($links);
234 $cpt = 0;
235 foreach ($links as $l) {
236 unset($l['linkdate']);
237 $l['id'] = $cpt;
238 $this->linkDB[$cpt++] = $l;
239 }
240
241 $this->linkDB->save($this->conf->get('resource.page_cache'));
242 $this->linkDB->reorder();
243
244 return true;
245 }
246
247 /**
248 * Rename tags starting with a '-' to work with tag exclusion search.
249 */
250 public function updateMethodRenameDashTags()
251 {
252 $linklist = $this->linkDB->filterSearch();
253 foreach ($linklist as $key => $link) {
254 $link['tags'] = preg_replace('/(^| )\-/', '$1', $link['tags']);
255 $link['tags'] = implode(' ', array_unique(LinkFilter::tagsStrToArray($link['tags'], true)));
256 $this->linkDB[$key] = $link;
257 }
258 $this->linkDB->save($this->conf->get('resource.page_cache'));
259 return true;
260 }
261
262 /**
263 * Initialize API settings:
264 * - api.enabled: true
265 * - api.secret: generated secret
266 */
267 public function updateMethodApiSettings()
268 {
269 if ($this->conf->exists('api.secret')) {
270 return true;
271 }
272
273 $this->conf->set('api.enabled', true);
274 $this->conf->set(
275 'api.secret',
276 generate_api_secret(
277 $this->conf->get('credentials.login'),
278 $this->conf->get('credentials.salt')
279 )
280 );
281 $this->conf->write($this->isLoggedIn);
282 return true;
283 }
284
285 /**
286 * New setting: theme name. If the default theme is used, nothing to do.
287 *
288 * If the user uses a custom theme, raintpl_tpl dir is updated to the parent directory,
289 * and the current theme is set as default in the theme setting.
290 *
291 * @return bool true if the update is successful, false otherwise.
292 */
293 public function updateMethodDefaultTheme()
294 {
295 // raintpl_tpl isn't the root template directory anymore.
296 // We run the update only if this folder still contains the template files.
297 $tplDir = $this->conf->get('resource.raintpl_tpl');
298 $tplFile = $tplDir . '/linklist.html';
299 if (! file_exists($tplFile)) {
300 return true;
301 }
302
303 $parent = dirname($tplDir);
304 $this->conf->set('resource.raintpl_tpl', $parent);
305 $this->conf->set('resource.theme', trim(str_replace($parent, '', $tplDir), '/'));
306 $this->conf->write($this->isLoggedIn);
307
308 // Dependency injection gore
309 RainTPL::$tpl_dir = $tplDir;
310
311 return true;
312 }
313
314 /**
315 * Move the file to inc/user.css to data/user.css.
316 *
317 * Note: Due to hardcoded paths, it's not unit testable. But one line of code should be fine.
318 *
319 * @return bool true if the update is successful, false otherwise.
320 */
321 public function updateMethodMoveUserCss()
322 {
323 if (! is_file('inc/user.css')) {
324 return true;
325 }
326
327 return rename('inc/user.css', 'data/user.css');
328 }
329
330 /**
331 * While the new default theme is in an unstable state
332 * continue to use the vintage theme
333 */
334 public function updateMethodDefaultThemeVintage()
335 {
336 if ($this->conf->get('resource.theme') !== 'default') {
337 return true;
338 }
339 $this->conf->set('resource.theme', 'vintage');
340 $this->conf->write($this->isLoggedIn);
341
342 return true;
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 /**
369 * Class UpdaterException.
370 */
371 class UpdaterException extends Exception
372 {
373 /**
374 * @var string Method where the error occurred.
375 */
376 protected $method;
377
378 /**
379 * @var Exception The parent exception.
380 */
381 protected $previous;
382
383 /**
384 * Constructor.
385 *
386 * @param string $message Force the error message if set.
387 * @param string $method Method where the error occurred.
388 * @param Exception|bool $previous Parent exception.
389 */
390 public function __construct($message = '', $method = '', $previous = false)
391 {
392 $this->method = $method;
393 $this->previous = $previous;
394 $this->message = $this->buildMessage($message);
395 }
396
397 /**
398 * Build the exception error message.
399 *
400 * @param string $message Optional given error message.
401 *
402 * @return string The built error message.
403 */
404 private function buildMessage($message)
405 {
406 $out = '';
407 if (! empty($message)) {
408 $out .= $message . PHP_EOL;
409 }
410
411 if (! empty($this->method)) {
412 $out .= 'An error occurred while running the update '. $this->method . PHP_EOL;
413 }
414
415 if (! empty($this->previous)) {
416 $out .= ' '. $this->previous->getMessage();
417 }
418
419 return $out;
420 }
421 }
422
423 /**
424 * Read the updates file, and return already done updates.
425 *
426 * @param string $updatesFilepath Updates file path.
427 *
428 * @return array Already done update methods.
429 */
430 function read_updates_file($updatesFilepath)
431 {
432 if (! empty($updatesFilepath) && is_file($updatesFilepath)) {
433 $content = file_get_contents($updatesFilepath);
434 if (! empty($content)) {
435 return explode(';', $content);
436 }
437 }
438 return array();
439 }
440
441 /**
442 * Write updates file.
443 *
444 * @param string $updatesFilepath Updates file path.
445 * @param array $updates Updates array to write.
446 *
447 * @throws Exception Couldn't write version number.
448 */
449 function write_updates_file($updatesFilepath, $updates)
450 {
451 if (empty($updatesFilepath)) {
452 throw new Exception('Updates file path is not set, can\'t write updates.');
453 }
454
455 $res = file_put_contents($updatesFilepath, implode(';', $updates));
456 if ($res === false) {
457 throw new Exception('Unable to write updates in '. $updatesFilepath . '.');
458 }
459 }