DatabaseDAO.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. //MySQL:
  153. $sql = <<<'SQL'
  154. SELECT SUM(data_length + index_length)
  155. FROM information_schema.TABLES WHERE table_schema=:table_schema
  156. SQL;
  157. $values = [':table_schema' => $db['base']];
  158. if (!$all) {
  159. $sql .= ' AND table_name LIKE :table_name';
  160. $values[':table_name'] = $this->pdo->prefix() . '%';
  161. }
  162. $res = $this->fetchColumn($sql, 0, $values);
  163. return isset($res[0]) ? (int)($res[0]) : -1;
  164. }
  165. public function optimize(): bool {
  166. $ok = true;
  167. $tables = ['category', 'feed', 'entry', 'entrytmp', 'tag', 'entrytag'];
  168. foreach ($tables as $table) {
  169. $sql = 'OPTIMIZE TABLE `_' . $table . '`'; //MySQL
  170. $stm = $this->pdo->query($sql);
  171. if ($stm == false || $stm->fetchAll(PDO::FETCH_ASSOC) == false) {
  172. $ok = false;
  173. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  174. Minz_Log::warning(__METHOD__ . ' error: ' . $sql . ' : ' . json_encode($info));
  175. }
  176. }
  177. return $ok;
  178. }
  179. public function minorDbMaintenance(): void {
  180. $catDAO = FreshRSS_Factory::createCategoryDao();
  181. $catDAO->resetDefaultCategoryName();
  182. }
  183. private static function stdError(string $error): bool {
  184. if (defined('STDERR')) {
  185. fwrite(STDERR, $error . "\n");
  186. }
  187. Minz_Log::error($error);
  188. return false;
  189. }
  190. public const SQLITE_EXPORT = 1;
  191. public const SQLITE_IMPORT = 2;
  192. public function dbCopy(string $filename, int $mode, bool $clearFirst = false): bool {
  193. if (!extension_loaded('pdo_sqlite')) {
  194. return self::stdError('PHP extension pdo_sqlite is missing!');
  195. }
  196. $error = '';
  197. $userDAO = FreshRSS_Factory::createUserDao();
  198. $catDAO = FreshRSS_Factory::createCategoryDao();
  199. $feedDAO = FreshRSS_Factory::createFeedDao();
  200. $entryDAO = FreshRSS_Factory::createEntryDao();
  201. $tagDAO = FreshRSS_Factory::createTagDao();
  202. switch ($mode) {
  203. case self::SQLITE_EXPORT:
  204. if (@filesize($filename) > 0) {
  205. $error = 'Error: SQLite export file already exists: ' . $filename;
  206. }
  207. break;
  208. case self::SQLITE_IMPORT:
  209. if (!is_readable($filename)) {
  210. $error = 'Error: SQLite import file is not readable: ' . $filename;
  211. } elseif ($clearFirst) {
  212. $userDAO->deleteUser();
  213. if ($this->pdo->dbType() === 'sqlite') {
  214. //We cannot just delete the .sqlite file otherwise PDO gets buggy.
  215. //SQLite is the only one with database-level optimization, instead of at table level.
  216. $this->optimize();
  217. }
  218. } else {
  219. $nbEntries = $entryDAO->countUnreadRead();
  220. if (!empty($nbEntries['all'])) {
  221. $error = 'Error: Destination database already contains some entries!';
  222. }
  223. }
  224. break;
  225. default:
  226. $error = 'Invalid copy mode!';
  227. break;
  228. }
  229. if ($error != '') {
  230. return self::stdError($error);
  231. }
  232. $sqlite = null;
  233. try {
  234. $sqlite = new Minz_PdoSqlite('sqlite:' . $filename);
  235. } catch (Exception $e) {
  236. $error = 'Error while initialising SQLite copy: ' . $e->getMessage();
  237. return self::stdError($error);
  238. }
  239. Minz_ModelPdo::clean();
  240. $userDAOSQLite = new FreshRSS_UserDAO('', $sqlite);
  241. $categoryDAOSQLite = new FreshRSS_CategoryDAOSQLite('', $sqlite);
  242. $feedDAOSQLite = new FreshRSS_FeedDAOSQLite('', $sqlite);
  243. $entryDAOSQLite = new FreshRSS_EntryDAOSQLite('', $sqlite);
  244. $tagDAOSQLite = new FreshRSS_TagDAOSQLite('', $sqlite);
  245. switch ($mode) {
  246. case self::SQLITE_EXPORT:
  247. $userFrom = $userDAO; $userTo = $userDAOSQLite;
  248. $catFrom = $catDAO; $catTo = $categoryDAOSQLite;
  249. $feedFrom = $feedDAO; $feedTo = $feedDAOSQLite;
  250. $entryFrom = $entryDAO; $entryTo = $entryDAOSQLite;
  251. $tagFrom = $tagDAO; $tagTo = $tagDAOSQLite;
  252. break;
  253. case self::SQLITE_IMPORT:
  254. $userFrom = $userDAOSQLite; $userTo = $userDAO;
  255. $catFrom = $categoryDAOSQLite; $catTo = $catDAO;
  256. $feedFrom = $feedDAOSQLite; $feedTo = $feedDAO;
  257. $entryFrom = $entryDAOSQLite; $entryTo = $entryDAO;
  258. $tagFrom = $tagDAOSQLite; $tagTo = $tagDAO;
  259. break;
  260. default:
  261. return false;
  262. }
  263. $idMaps = [];
  264. if (defined('STDERR')) {
  265. fwrite(STDERR, "Start SQL copy…\n");
  266. }
  267. $userTo->createUser();
  268. $catTo->beginTransaction();
  269. foreach ($catFrom->selectAll() as $category) {
  270. $cat = $catTo->searchByName($category['name']); //Useful for the default category
  271. if ($cat != null) {
  272. $catId = $cat->id();
  273. } else {
  274. $catId = $catTo->addCategory($category);
  275. if ($catId == false) {
  276. $error = 'Error during SQLite copy of categories!';
  277. return self::stdError($error);
  278. }
  279. }
  280. $idMaps['c' . $category['id']] = $catId;
  281. }
  282. foreach ($feedFrom->selectAll() as $feed) {
  283. $feed['category'] = empty($idMaps['c' . $feed['category']]) ? FreshRSS_CategoryDAO::DEFAULTCATEGORYID : $idMaps['c' . $feed['category']];
  284. $feedId = $feedTo->addFeed($feed);
  285. if ($feedId == false) {
  286. $error = 'Error during SQLite copy of feeds!';
  287. return self::stdError($error);
  288. }
  289. $idMaps['f' . $feed['id']] = $feedId;
  290. }
  291. $catTo->commit();
  292. $nbEntries = $entryFrom->count();
  293. $n = 0;
  294. $entryTo->beginTransaction();
  295. foreach ($entryFrom->selectAll() as $entry) {
  296. $n++;
  297. if (!empty($idMaps['f' . $entry['id_feed']])) {
  298. $entry['id_feed'] = $idMaps['f' . $entry['id_feed']];
  299. if (!$entryTo->addEntry($entry, false)) {
  300. $error = 'Error during SQLite copy of entries!';
  301. return self::stdError($error);
  302. }
  303. }
  304. if ($n % 100 === 1 && defined('STDERR')) { //Display progression
  305. fwrite(STDERR, "\033[0G" . $n . '/' . $nbEntries);
  306. }
  307. }
  308. if (defined('STDERR')) {
  309. fwrite(STDERR, "\033[0G" . $n . '/' . $nbEntries . "\n");
  310. }
  311. $entryTo->commit();
  312. $feedTo->updateCachedValues();
  313. $idMaps = [];
  314. $tagTo->beginTransaction();
  315. foreach ($tagFrom->selectAll() as $tag) {
  316. $tagId = $tagTo->addTag($tag);
  317. if ($tagId == false) {
  318. $error = 'Error during SQLite copy of tags!';
  319. return self::stdError($error);
  320. }
  321. $idMaps['t' . $tag['id']] = $tagId;
  322. }
  323. foreach ($tagFrom->selectEntryTag() as $entryTag) {
  324. if (!empty($idMaps['t' . $entryTag['id_tag']])) {
  325. $entryTag['id_tag'] = $idMaps['t' . $entryTag['id_tag']];
  326. if (!$tagTo->tagEntry($entryTag['id_tag'], $entryTag['id_entry'])) {
  327. $error = 'Error during SQLite copy of entry-tags!';
  328. return self::stdError($error);
  329. }
  330. }
  331. }
  332. $tagTo->commit();
  333. return true;
  334. }
  335. }