Updater.php 12 KB

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