DatabaseDAO.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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_once(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. private function ensureYear2038Compatible(): bool {
  188. if ($this->pdo->dbType() !== 'sqlite') {
  189. include_once(APP_PATH . '/SQL/install.sql.' . $this->pdo->dbType() . '.php');
  190. if ($this->pdo->exec($GLOBALS['SQL_UPDATE_YEAR_2038']) === false) { //FreshRSS 1.23
  191. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($this->pdo->errorInfo()));
  192. return false;
  193. }
  194. }
  195. return true;
  196. }
  197. public function minorDbMaintenance(): void {
  198. $catDAO = FreshRSS_Factory::createCategoryDao();
  199. $catDAO->resetDefaultCategoryName();
  200. $this->ensureYear2038Compatible();
  201. }
  202. private static function stdError(string $error): bool {
  203. if (defined('STDERR')) {
  204. fwrite(STDERR, $error . "\n");
  205. }
  206. Minz_Log::error($error);
  207. return false;
  208. }
  209. public const SQLITE_EXPORT = 1;
  210. public const SQLITE_IMPORT = 2;
  211. public function dbCopy(string $filename, int $mode, bool $clearFirst = false): bool {
  212. if (!extension_loaded('pdo_sqlite')) {
  213. return self::stdError('PHP extension pdo_sqlite is missing!');
  214. }
  215. $error = '';
  216. $userDAO = FreshRSS_Factory::createUserDao();
  217. $catDAO = FreshRSS_Factory::createCategoryDao();
  218. $feedDAO = FreshRSS_Factory::createFeedDao();
  219. $entryDAO = FreshRSS_Factory::createEntryDao();
  220. $tagDAO = FreshRSS_Factory::createTagDao();
  221. switch ($mode) {
  222. case self::SQLITE_EXPORT:
  223. if (@filesize($filename) > 0) {
  224. $error = 'Error: SQLite export file already exists: ' . $filename;
  225. }
  226. break;
  227. case self::SQLITE_IMPORT:
  228. if (!is_readable($filename)) {
  229. $error = 'Error: SQLite import file is not readable: ' . $filename;
  230. } elseif ($clearFirst) {
  231. $userDAO->deleteUser();
  232. if ($this->pdo->dbType() === 'sqlite') {
  233. //We cannot just delete the .sqlite file otherwise PDO gets buggy.
  234. //SQLite is the only one with database-level optimization, instead of at table level.
  235. $this->optimize();
  236. }
  237. } else {
  238. $nbEntries = $entryDAO->countUnreadRead();
  239. if (!empty($nbEntries['all'])) {
  240. $error = 'Error: Destination database already contains some entries!';
  241. }
  242. }
  243. break;
  244. default:
  245. $error = 'Invalid copy mode!';
  246. break;
  247. }
  248. if ($error != '') {
  249. return self::stdError($error);
  250. }
  251. $sqlite = null;
  252. try {
  253. $sqlite = new Minz_PdoSqlite('sqlite:' . $filename);
  254. } catch (Exception $e) {
  255. $error = 'Error while initialising SQLite copy: ' . $e->getMessage();
  256. return self::stdError($error);
  257. }
  258. Minz_ModelPdo::clean();
  259. $userDAOSQLite = new FreshRSS_UserDAO('', $sqlite);
  260. $categoryDAOSQLite = new FreshRSS_CategoryDAOSQLite('', $sqlite);
  261. $feedDAOSQLite = new FreshRSS_FeedDAOSQLite('', $sqlite);
  262. $entryDAOSQLite = new FreshRSS_EntryDAOSQLite('', $sqlite);
  263. $tagDAOSQLite = new FreshRSS_TagDAOSQLite('', $sqlite);
  264. switch ($mode) {
  265. case self::SQLITE_EXPORT:
  266. $userFrom = $userDAO; $userTo = $userDAOSQLite;
  267. $catFrom = $catDAO; $catTo = $categoryDAOSQLite;
  268. $feedFrom = $feedDAO; $feedTo = $feedDAOSQLite;
  269. $entryFrom = $entryDAO; $entryTo = $entryDAOSQLite;
  270. $tagFrom = $tagDAO; $tagTo = $tagDAOSQLite;
  271. break;
  272. case self::SQLITE_IMPORT:
  273. $userFrom = $userDAOSQLite; $userTo = $userDAO;
  274. $catFrom = $categoryDAOSQLite; $catTo = $catDAO;
  275. $feedFrom = $feedDAOSQLite; $feedTo = $feedDAO;
  276. $entryFrom = $entryDAOSQLite; $entryTo = $entryDAO;
  277. $tagFrom = $tagDAOSQLite; $tagTo = $tagDAO;
  278. break;
  279. default:
  280. return false;
  281. }
  282. $idMaps = [];
  283. if (defined('STDERR')) {
  284. fwrite(STDERR, "Start SQL copy…\n");
  285. }
  286. $userTo->createUser();
  287. $catTo->beginTransaction();
  288. foreach ($catFrom->selectAll() as $category) {
  289. $cat = $catTo->searchByName($category['name']); //Useful for the default category
  290. if ($cat != null) {
  291. $catId = $cat->id();
  292. } else {
  293. $catId = $catTo->addCategory($category);
  294. if ($catId == false) {
  295. $error = 'Error during SQLite copy of categories!';
  296. return self::stdError($error);
  297. }
  298. }
  299. $idMaps['c' . $category['id']] = $catId;
  300. }
  301. foreach ($feedFrom->selectAll() as $feed) {
  302. $feed['category'] = empty($idMaps['c' . $feed['category']]) ? FreshRSS_CategoryDAO::DEFAULTCATEGORYID : $idMaps['c' . $feed['category']];
  303. $feedId = $feedTo->addFeed($feed);
  304. if ($feedId == false) {
  305. $error = 'Error during SQLite copy of feeds!';
  306. return self::stdError($error);
  307. }
  308. $idMaps['f' . $feed['id']] = $feedId;
  309. }
  310. $catTo->commit();
  311. $nbEntries = $entryFrom->count();
  312. $n = 0;
  313. $entryTo->beginTransaction();
  314. foreach ($entryFrom->selectAll() as $entry) {
  315. $n++;
  316. if (!empty($idMaps['f' . $entry['id_feed']])) {
  317. $entry['id_feed'] = $idMaps['f' . $entry['id_feed']];
  318. if (!$entryTo->addEntry($entry, false)) {
  319. $error = 'Error during SQLite copy of entries!';
  320. return self::stdError($error);
  321. }
  322. }
  323. if ($n % 100 === 1 && defined('STDERR')) { //Display progression
  324. fwrite(STDERR, "\033[0G" . $n . '/' . $nbEntries);
  325. }
  326. }
  327. if (defined('STDERR')) {
  328. fwrite(STDERR, "\033[0G" . $n . '/' . $nbEntries . "\n");
  329. }
  330. $entryTo->commit();
  331. $feedTo->updateCachedValues();
  332. $idMaps = [];
  333. $tagTo->beginTransaction();
  334. foreach ($tagFrom->selectAll() as $tag) {
  335. $tagId = $tagTo->addTag($tag);
  336. if ($tagId == false) {
  337. $error = 'Error during SQLite copy of tags!';
  338. return self::stdError($error);
  339. }
  340. $idMaps['t' . $tag['id']] = $tagId;
  341. }
  342. foreach ($tagFrom->selectEntryTag() as $entryTag) {
  343. if (!empty($idMaps['t' . $entryTag['id_tag']])) {
  344. $entryTag['id_tag'] = $idMaps['t' . $entryTag['id_tag']];
  345. if (!$tagTo->tagEntry($entryTag['id_tag'], $entryTag['id_entry'])) {
  346. $error = 'Error during SQLite copy of entry-tags!';
  347. return self::stdError($error);
  348. }
  349. }
  350. }
  351. $tagTo->commit();
  352. return true;
  353. }
  354. }