Updater.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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. /**
  252. * Class UpdaterException.
  253. */
  254. class UpdaterException extends Exception
  255. {
  256. /**
  257. * @var string Method where the error occurred.
  258. */
  259. protected $method;
  260. /**
  261. * @var Exception The parent exception.
  262. */
  263. protected $previous;
  264. /**
  265. * Constructor.
  266. *
  267. * @param string $message Force the error message if set.
  268. * @param string $method Method where the error occurred.
  269. * @param Exception|bool $previous Parent exception.
  270. */
  271. public function __construct($message = '', $method = '', $previous = false)
  272. {
  273. $this->method = $method;
  274. $this->previous = $previous;
  275. $this->message = $this->buildMessage($message);
  276. }
  277. /**
  278. * Build the exception error message.
  279. *
  280. * @param string $message Optional given error message.
  281. *
  282. * @return string The built error message.
  283. */
  284. private function buildMessage($message)
  285. {
  286. $out = '';
  287. if (! empty($message)) {
  288. $out .= $message . PHP_EOL;
  289. }
  290. if (! empty($this->method)) {
  291. $out .= 'An error occurred while running the update '. $this->method . PHP_EOL;
  292. }
  293. if (! empty($this->previous)) {
  294. $out .= ' '. $this->previous->getMessage();
  295. }
  296. return $out;
  297. }
  298. }
  299. /**
  300. * Read the updates file, and return already done updates.
  301. *
  302. * @param string $updatesFilepath Updates file path.
  303. *
  304. * @return array Already done update methods.
  305. */
  306. function read_updates_file($updatesFilepath)
  307. {
  308. if (! empty($updatesFilepath) && is_file($updatesFilepath)) {
  309. $content = file_get_contents($updatesFilepath);
  310. if (! empty($content)) {
  311. return explode(';', $content);
  312. }
  313. }
  314. return array();
  315. }
  316. /**
  317. * Write updates file.
  318. *
  319. * @param string $updatesFilepath Updates file path.
  320. * @param array $updates Updates array to write.
  321. *
  322. * @throws Exception Couldn't write version number.
  323. */
  324. function write_updates_file($updatesFilepath, $updates)
  325. {
  326. if (empty($updatesFilepath)) {
  327. throw new Exception('Updates file path is not set, can\'t write updates.');
  328. }
  329. $res = file_put_contents($updatesFilepath, implode(';', $updates));
  330. if ($res === false) {
  331. throw new Exception('Unable to write updates in '. $updatesFilepath . '.');
  332. }
  333. }