Updater.php 17 KB

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