DatabaseDAO.php 11 KB

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