DatabaseDAO.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. <?php
  2. /**
  3. * This class is used to test database is well-constructed.
  4. */
  5. class FreshRSS_DatabaseDAO extends Minz_ModelPdo {
  6. //MySQL error codes
  7. public const ER_BAD_FIELD_ERROR = '42S22';
  8. public const ER_BAD_TABLE_ERROR = '42S02';
  9. public const ER_DATA_TOO_LONG = '1406';
  10. /**
  11. * Based on SQLite SQLITE_MAX_VARIABLE_NUMBER
  12. */
  13. public const MAX_VARIABLE_NUMBER = 998;
  14. //MySQL InnoDB maximum index length for UTF8MB4
  15. //https://dev.mysql.com/doc/refman/8.0/en/innodb-restrictions.html
  16. public const LENGTH_INDEX_UNICODE = 191;
  17. public function create(): string {
  18. require(APP_PATH . '/SQL/install.sql.' . $this->pdo->dbType() . '.php');
  19. $db = FreshRSS_Context::$system_conf->db;
  20. try {
  21. $sql = sprintf($GLOBALS['SQL_CREATE_DB'], empty($db['base']) ? '' : $db['base']);
  22. return $this->pdo->exec($sql) === false ? 'Error during CREATE DATABASE' : '';
  23. } catch (Exception $e) {
  24. syslog(LOG_DEBUG, __method__ . ' notice: ' . $e->getMessage());
  25. return $e->getMessage();
  26. }
  27. }
  28. public function testConnection(): string {
  29. try {
  30. $sql = 'SELECT 1';
  31. $stm = $this->pdo->query($sql);
  32. if ($stm === false) {
  33. return 'Error during SQL connection test!';
  34. }
  35. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  36. return $res == false ? 'Error during SQL connection fetch test!' : '';
  37. } catch (Exception $e) {
  38. syslog(LOG_DEBUG, __method__ . ' warning: ' . $e->getMessage());
  39. return $e->getMessage();
  40. }
  41. }
  42. public function tablesAreCorrect(): bool {
  43. $res = $this->fetchAssoc('SHOW TABLES');
  44. if ($res == null) {
  45. return false;
  46. }
  47. $tables = [
  48. $this->pdo->prefix() . 'category' => false,
  49. $this->pdo->prefix() . 'feed' => false,
  50. $this->pdo->prefix() . 'entry' => false,
  51. $this->pdo->prefix() . 'entrytmp' => false,
  52. $this->pdo->prefix() . 'tag' => false,
  53. $this->pdo->prefix() . 'entrytag' => false,
  54. ];
  55. foreach ($res as $value) {
  56. $tables[array_pop($value)] = true;
  57. }
  58. return count(array_keys($tables, true, true)) === count($tables);
  59. }
  60. /** @return array<array<string,string|int|bool|null>> */
  61. public function getSchema(string $table): array {
  62. $res = $this->fetchAssoc('DESC `_' . $table . '`');
  63. return $res == null ? [] : $this->listDaoToSchema($res);
  64. }
  65. /** @param array<string> $schema */
  66. public function checkTable(string $table, array $schema): bool {
  67. $columns = $this->getSchema($table);
  68. if (count($columns) === 0 || count($schema) === 0) {
  69. return false;
  70. }
  71. $ok = count($columns) === count($schema);
  72. foreach ($columns as $c) {
  73. $ok &= in_array($c['name'], $schema, true);
  74. }
  75. return (bool)$ok;
  76. }
  77. public function categoryIsCorrect(): bool {
  78. return $this->checkTable('category', ['id', 'name']);
  79. }
  80. public function feedIsCorrect(): bool {
  81. return $this->checkTable('feed', [
  82. 'id',
  83. 'url',
  84. 'category',
  85. 'name',
  86. 'website',
  87. 'description',
  88. 'lastUpdate',
  89. 'priority',
  90. 'pathEntries',
  91. 'httpAuth',
  92. 'error',
  93. 'ttl',
  94. 'attributes',
  95. 'cache_nbEntries',
  96. 'cache_nbUnreads',
  97. ]);
  98. }
  99. public function entryIsCorrect(): bool {
  100. return $this->checkTable('entry', [
  101. 'id',
  102. 'guid',
  103. 'title',
  104. 'author',
  105. 'content_bin',
  106. 'link',
  107. 'date',
  108. 'lastSeen',
  109. 'hash',
  110. 'is_read',
  111. 'is_favorite',
  112. 'id_feed',
  113. 'tags',
  114. ]);
  115. }
  116. public function entrytmpIsCorrect(): bool {
  117. return $this->checkTable('entrytmp', [
  118. 'id', 'guid', 'title', 'author', 'content_bin', 'link', 'date', 'lastSeen', 'hash', 'is_read', 'is_favorite', 'id_feed', 'tags'
  119. ]);
  120. }
  121. public function tagIsCorrect(): bool {
  122. return $this->checkTable('tag', ['id', 'name', 'attributes']);
  123. }
  124. public function entrytagIsCorrect(): bool {
  125. return $this->checkTable('entrytag', ['id_tag', 'id_entry']);
  126. }
  127. /**
  128. * @param array<string,string|int|bool|null> $dao
  129. * @return array{'name':string,'type':string,'notnull':bool,'default':mixed}
  130. */
  131. public function daoToSchema(array $dao): array {
  132. return [
  133. 'name' => (string)($dao['Field']),
  134. 'type' => strtolower((string)($dao['Type'])),
  135. 'notnull' => (bool)$dao['Null'],
  136. 'default' => $dao['Default'],
  137. ];
  138. }
  139. /**
  140. * @param array<array<string,string|int|bool|null>> $listDAO
  141. * @return array<array<string,string|int|bool|null>>
  142. */
  143. public function listDaoToSchema(array $listDAO): array {
  144. $list = [];
  145. foreach ($listDAO as $dao) {
  146. $list[] = $this->daoToSchema($dao);
  147. }
  148. return $list;
  149. }
  150. public function size(bool $all = false): int {
  151. $db = FreshRSS_Context::$system_conf->db;
  152. // MariaDB does not refresh size information automatically
  153. $sql = <<<'SQL'
  154. ANALYZE TABLE `_category`, `_feed`, `_entry`, `_entrytmp`, `_tag`, `_entrytag`
  155. SQL;
  156. $stm = $this->pdo->query($sql);
  157. if ($stm !== false) {
  158. $stm->fetchAll();
  159. }
  160. //MySQL:
  161. $sql = <<<'SQL'
  162. SELECT SUM(DATA_LENGTH + INDEX_LENGTH + DATA_FREE)
  163. FROM information_schema.TABLES WHERE TABLE_SCHEMA=:table_schema
  164. SQL;
  165. $values = [':table_schema' => $db['base']];
  166. if (!$all) {
  167. $sql .= ' AND table_name LIKE :table_name';
  168. $values[':table_name'] = $this->pdo->prefix() . '%';
  169. }
  170. $res = $this->fetchColumn($sql, 0, $values);
  171. return isset($res[0]) ? (int)($res[0]) : -1;
  172. }
  173. public function optimize(): bool {
  174. $ok = true;
  175. $tables = ['category', 'feed', 'entry', 'entrytmp', 'tag', 'entrytag'];
  176. foreach ($tables as $table) {
  177. $sql = 'OPTIMIZE TABLE `_' . $table . '`'; //MySQL
  178. $stm = $this->pdo->query($sql);
  179. if ($stm == false || $stm->fetchAll(PDO::FETCH_ASSOC) == false) {
  180. $ok = false;
  181. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  182. Minz_Log::warning(__METHOD__ . ' error: ' . $sql . ' : ' . json_encode($info));
  183. }
  184. }
  185. return $ok;
  186. }
  187. public function minorDbMaintenance(): void {
  188. $catDAO = FreshRSS_Factory::createCategoryDao();
  189. $catDAO->resetDefaultCategoryName();
  190. }
  191. private static function stdError(string $error): bool {
  192. if (defined('STDERR')) {
  193. fwrite(STDERR, $error . "\n");
  194. }
  195. Minz_Log::error($error);
  196. return false;
  197. }
  198. public const SQLITE_EXPORT = 1;
  199. public const SQLITE_IMPORT = 2;
  200. public function dbCopy(string $filename, int $mode, bool $clearFirst = false): bool {
  201. if (!extension_loaded('pdo_sqlite')) {
  202. return self::stdError('PHP extension pdo_sqlite is missing!');
  203. }
  204. $error = '';
  205. $userDAO = FreshRSS_Factory::createUserDao();
  206. $catDAO = FreshRSS_Factory::createCategoryDao();
  207. $feedDAO = FreshRSS_Factory::createFeedDao();
  208. $entryDAO = FreshRSS_Factory::createEntryDao();
  209. $tagDAO = FreshRSS_Factory::createTagDao();
  210. switch ($mode) {
  211. case self::SQLITE_EXPORT:
  212. if (@filesize($filename) > 0) {
  213. $error = 'Error: SQLite export file already exists: ' . $filename;
  214. }
  215. break;
  216. case self::SQLITE_IMPORT:
  217. if (!is_readable($filename)) {
  218. $error = 'Error: SQLite import file is not readable: ' . $filename;
  219. } elseif ($clearFirst) {
  220. $userDAO->deleteUser();
  221. if ($this->pdo->dbType() === 'sqlite') {
  222. //We cannot just delete the .sqlite file otherwise PDO gets buggy.
  223. //SQLite is the only one with database-level optimization, instead of at table level.
  224. $this->optimize();
  225. }
  226. } else {
  227. $nbEntries = $entryDAO->countUnreadRead();
  228. if (!empty($nbEntries['all'])) {
  229. $error = 'Error: Destination database already contains some entries!';
  230. }
  231. }
  232. break;
  233. default:
  234. $error = 'Invalid copy mode!';
  235. break;
  236. }
  237. if ($error != '') {
  238. return self::stdError($error);
  239. }
  240. $sqlite = null;
  241. try {
  242. $sqlite = new Minz_PdoSqlite('sqlite:' . $filename);
  243. } catch (Exception $e) {
  244. $error = 'Error while initialising SQLite copy: ' . $e->getMessage();
  245. return self::stdError($error);
  246. }
  247. Minz_ModelPdo::clean();
  248. $userDAOSQLite = new FreshRSS_UserDAO('', $sqlite);
  249. $categoryDAOSQLite = new FreshRSS_CategoryDAOSQLite('', $sqlite);
  250. $feedDAOSQLite = new FreshRSS_FeedDAOSQLite('', $sqlite);
  251. $entryDAOSQLite = new FreshRSS_EntryDAOSQLite('', $sqlite);
  252. $tagDAOSQLite = new FreshRSS_TagDAOSQLite('', $sqlite);
  253. switch ($mode) {
  254. case self::SQLITE_EXPORT:
  255. $userFrom = $userDAO; $userTo = $userDAOSQLite;
  256. $catFrom = $catDAO; $catTo = $categoryDAOSQLite;
  257. $feedFrom = $feedDAO; $feedTo = $feedDAOSQLite;
  258. $entryFrom = $entryDAO; $entryTo = $entryDAOSQLite;
  259. $tagFrom = $tagDAO; $tagTo = $tagDAOSQLite;
  260. break;
  261. case self::SQLITE_IMPORT:
  262. $userFrom = $userDAOSQLite; $userTo = $userDAO;
  263. $catFrom = $categoryDAOSQLite; $catTo = $catDAO;
  264. $feedFrom = $feedDAOSQLite; $feedTo = $feedDAO;
  265. $entryFrom = $entryDAOSQLite; $entryTo = $entryDAO;
  266. $tagFrom = $tagDAOSQLite; $tagTo = $tagDAO;
  267. break;
  268. default:
  269. return false;
  270. }
  271. $idMaps = [];
  272. if (defined('STDERR')) {
  273. fwrite(STDERR, "Start SQL copy…\n");
  274. }
  275. $userTo->createUser();
  276. $catTo->beginTransaction();
  277. foreach ($catFrom->selectAll() as $category) {
  278. $cat = $catTo->searchByName($category['name']); //Useful for the default category
  279. if ($cat != null) {
  280. $catId = $cat->id();
  281. } else {
  282. $catId = $catTo->addCategory($category);
  283. if ($catId == false) {
  284. $error = 'Error during SQLite copy of categories!';
  285. return self::stdError($error);
  286. }
  287. }
  288. $idMaps['c' . $category['id']] = $catId;
  289. }
  290. foreach ($feedFrom->selectAll() as $feed) {
  291. $feed['category'] = empty($idMaps['c' . $feed['category']]) ? FreshRSS_CategoryDAO::DEFAULTCATEGORYID : $idMaps['c' . $feed['category']];
  292. $feedId = $feedTo->addFeed($feed);
  293. if ($feedId == false) {
  294. $error = 'Error during SQLite copy of feeds!';
  295. return self::stdError($error);
  296. }
  297. $idMaps['f' . $feed['id']] = $feedId;
  298. }
  299. $catTo->commit();
  300. $nbEntries = $entryFrom->count();
  301. $n = 0;
  302. $entryTo->beginTransaction();
  303. foreach ($entryFrom->selectAll() as $entry) {
  304. $n++;
  305. if (!empty($idMaps['f' . $entry['id_feed']])) {
  306. $entry['id_feed'] = $idMaps['f' . $entry['id_feed']];
  307. if (!$entryTo->addEntry($entry, false)) {
  308. $error = 'Error during SQLite copy of entries!';
  309. return self::stdError($error);
  310. }
  311. }
  312. if ($n % 100 === 1 && defined('STDERR')) { //Display progression
  313. fwrite(STDERR, "\033[0G" . $n . '/' . $nbEntries);
  314. }
  315. }
  316. if (defined('STDERR')) {
  317. fwrite(STDERR, "\033[0G" . $n . '/' . $nbEntries . "\n");
  318. }
  319. $entryTo->commit();
  320. $feedTo->updateCachedValues();
  321. $idMaps = [];
  322. $tagTo->beginTransaction();
  323. foreach ($tagFrom->selectAll() as $tag) {
  324. $tagId = $tagTo->addTag($tag);
  325. if ($tagId == false) {
  326. $error = 'Error during SQLite copy of tags!';
  327. return self::stdError($error);
  328. }
  329. $idMaps['t' . $tag['id']] = $tagId;
  330. }
  331. foreach ($tagFrom->selectEntryTag() as $entryTag) {
  332. if (!empty($idMaps['t' . $entryTag['id_tag']])) {
  333. $entryTag['id_tag'] = $idMaps['t' . $entryTag['id_tag']];
  334. if (!$tagTo->tagEntry($entryTag['id_tag'], $entryTag['id_entry'])) {
  335. $error = 'Error during SQLite copy of entry-tags!';
  336. return self::stdError($error);
  337. }
  338. }
  339. }
  340. $tagTo->commit();
  341. return true;
  342. }
  343. }