Updater.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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 $link) {
  123. $link['tags'] = preg_replace('/(^| )\-/', '$1', $link['tags']);
  124. $link['tags'] = implode(' ', array_unique(LinkFilter::tagsStrToArray($link['tags'], true)));
  125. $this->linkDB[$link['linkdate']] = $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. /**
  195. * Class UpdaterException.
  196. */
  197. class UpdaterException extends Exception
  198. {
  199. /**
  200. * @var string Method where the error occurred.
  201. */
  202. protected $method;
  203. /**
  204. * @var Exception The parent exception.
  205. */
  206. protected $previous;
  207. /**
  208. * Constructor.
  209. *
  210. * @param string $message Force the error message if set.
  211. * @param string $method Method where the error occurred.
  212. * @param Exception|bool $previous Parent exception.
  213. */
  214. public function __construct($message = '', $method = '', $previous = false)
  215. {
  216. $this->method = $method;
  217. $this->previous = $previous;
  218. $this->message = $this->buildMessage($message);
  219. }
  220. /**
  221. * Build the exception error message.
  222. *
  223. * @param string $message Optional given error message.
  224. *
  225. * @return string The built error message.
  226. */
  227. private function buildMessage($message)
  228. {
  229. $out = '';
  230. if (! empty($message)) {
  231. $out .= $message . PHP_EOL;
  232. }
  233. if (! empty($this->method)) {
  234. $out .= 'An error occurred while running the update '. $this->method . PHP_EOL;
  235. }
  236. if (! empty($this->previous)) {
  237. $out .= ' '. $this->previous->getMessage();
  238. }
  239. return $out;
  240. }
  241. }
  242. /**
  243. * Read the updates file, and return already done updates.
  244. *
  245. * @param string $updatesFilepath Updates file path.
  246. *
  247. * @return array Already done update methods.
  248. */
  249. function read_updates_file($updatesFilepath)
  250. {
  251. if (! empty($updatesFilepath) && is_file($updatesFilepath)) {
  252. $content = file_get_contents($updatesFilepath);
  253. if (! empty($content)) {
  254. return explode(';', $content);
  255. }
  256. }
  257. return array();
  258. }
  259. /**
  260. * Write updates file.
  261. *
  262. * @param string $updatesFilepath Updates file path.
  263. * @param array $updates Updates array to write.
  264. *
  265. * @throws Exception Couldn't write version number.
  266. */
  267. function write_updates_file($updatesFilepath, $updates)
  268. {
  269. if (empty($updatesFilepath)) {
  270. throw new Exception('Updates file path is not set, can\'t write updates.');
  271. }
  272. $res = file_put_contents($updatesFilepath, implode(';', $updates));
  273. if ($res === false) {
  274. throw new Exception('Unable to write updates in '. $updatesFilepath . '.');
  275. }
  276. }