DatabaseDAO.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. const ER_BAD_FIELD_ERROR = '42S22';
  8. const ER_BAD_TABLE_ERROR = '42S02';
  9. const ER_DATA_TOO_LONG = '1406';
  10. /**
  11. * Based on SQLite SQLITE_MAX_VARIABLE_NUMBER
  12. */
  13. 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. 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 = array(
  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);
  74. }
  75. return (bool)$ok;
  76. }
  77. public function categoryIsCorrect(): bool {
  78. return $this->checkTable('category', array(
  79. 'id', 'name',
  80. ));
  81. }
  82. public function feedIsCorrect(): bool {
  83. return $this->checkTable('feed', array(
  84. 'id', 'url', 'category', 'name', 'website', 'description', 'lastUpdate',
  85. 'priority', 'pathEntries', 'httpAuth', 'error', 'ttl', 'attributes',
  86. 'cache_nbEntries', 'cache_nbUnreads',
  87. ));
  88. }
  89. public function entryIsCorrect(): bool {
  90. return $this->checkTable('entry', array(
  91. 'id', 'guid', 'title', 'author', 'content_bin', 'link', 'date', 'lastSeen', 'hash', 'is_read',
  92. 'is_favorite', 'id_feed', 'tags',
  93. ));
  94. }
  95. public function entrytmpIsCorrect(): bool {
  96. return $this->checkTable('entrytmp', array(
  97. 'id', 'guid', 'title', 'author', 'content_bin', 'link', 'date', 'lastSeen', 'hash', 'is_read',
  98. 'is_favorite', 'id_feed', 'tags',
  99. ));
  100. }
  101. public function tagIsCorrect(): bool {
  102. return $this->checkTable('tag', array(
  103. 'id', 'name', 'attributes',
  104. ));
  105. }
  106. public function entrytagIsCorrect(): bool {
  107. return $this->checkTable('entrytag', array(
  108. 'id_tag', 'id_entry',
  109. ));
  110. }
  111. /**
  112. * @param array<string,string|int|bool|null> $dao
  113. * @return array<string,string|int|bool|null>
  114. */
  115. public function daoToSchema(array $dao): array {
  116. return [
  117. 'name' => (string)($dao['Field']),
  118. 'type' => strtolower((string)($dao['Type'])),
  119. 'notnull' => (bool)$dao['Null'],
  120. 'default' => $dao['Default'],
  121. ];
  122. }
  123. /**
  124. * @param array<array<string,string|int|bool|null>> $listDAO
  125. * @return array<array<string,string|int|bool|null>>
  126. */
  127. public function listDaoToSchema(array $listDAO): array {
  128. $list = array();
  129. foreach ($listDAO as $dao) {
  130. $list[] = $this->daoToSchema($dao);
  131. }
  132. return $list;
  133. }
  134. public function size(bool $all = false): int {
  135. $db = FreshRSS_Context::$system_conf->db;
  136. //MySQL:
  137. $sql = <<<'SQL'
  138. SELECT SUM(data_length + index_length)
  139. FROM information_schema.TABLES WHERE table_schema=:table_schema
  140. SQL;
  141. $values = [':table_schema' => $db['base']];
  142. if (!$all) {
  143. $sql .= ' AND table_name LIKE :table_name';
  144. $values[':table_name'] = $this->pdo->prefix() . '%';
  145. }
  146. $res = $this->fetchColumn($sql, 0, $values);
  147. return isset($res[0]) ? (int)($res[0]) : -1;
  148. }
  149. public function optimize(): bool {
  150. $ok = true;
  151. $tables = array('category', 'feed', 'entry', 'entrytmp', 'tag', 'entrytag');
  152. foreach ($tables as $table) {
  153. $sql = 'OPTIMIZE TABLE `_' . $table . '`'; //MySQL
  154. $stm = $this->pdo->query($sql);
  155. if ($stm == false || $stm->fetchAll(PDO::FETCH_ASSOC) == false) {
  156. $ok = false;
  157. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  158. Minz_Log::warning(__METHOD__ . ' error: ' . $sql . ' : ' . json_encode($info));
  159. }
  160. }
  161. return $ok;
  162. }
  163. public function ensureCaseInsensitiveGuids(): bool {
  164. $ok = true;
  165. if ($this->pdo->dbType() === 'mysql') {
  166. include(APP_PATH . '/SQL/install.sql.mysql.php');
  167. $ok = false;
  168. try {
  169. $ok = $this->pdo->exec($GLOBALS['SQL_UPDATE_GUID_LATIN1_BIN']) !== false; //FreshRSS 1.12
  170. } catch (Exception $e) {
  171. $ok = false;
  172. Minz_Log::error(__METHOD__ . ' error: ' . $e->getMessage());
  173. }
  174. }
  175. return $ok;
  176. }
  177. public function minorDbMaintenance(): void {
  178. $catDAO = FreshRSS_Factory::createCategoryDao();
  179. $catDAO->resetDefaultCategoryName();
  180. $this->ensureCaseInsensitiveGuids();
  181. }
  182. private static function stdError(string $error): bool {
  183. if (defined('STDERR')) {
  184. fwrite(STDERR, $error . "\n");
  185. }
  186. Minz_Log::error($error);
  187. return false;
  188. }
  189. const SQLITE_EXPORT = 1;
  190. const SQLITE_IMPORT = 2;
  191. public function dbCopy(string $filename, int $mode, bool $clearFirst = false): bool {
  192. if (!extension_loaded('pdo_sqlite')) {
  193. return self::stdError('PHP extension pdo_sqlite is missing!');
  194. }
  195. $error = '';
  196. $userDAO = FreshRSS_Factory::createUserDao();
  197. $catDAO = FreshRSS_Factory::createCategoryDao();
  198. $feedDAO = FreshRSS_Factory::createFeedDao();
  199. $entryDAO = FreshRSS_Factory::createEntryDao();
  200. $tagDAO = FreshRSS_Factory::createTagDao();
  201. switch ($mode) {
  202. case self::SQLITE_EXPORT:
  203. if (@filesize($filename) > 0) {
  204. $error = 'Error: SQLite export file already exists: ' . $filename;
  205. }
  206. break;
  207. case self::SQLITE_IMPORT:
  208. if (!is_readable($filename)) {
  209. $error = 'Error: SQLite import file is not readable: ' . $filename;
  210. } elseif ($clearFirst) {
  211. $userDAO->deleteUser();
  212. if ($this->pdo->dbType() === 'sqlite') {
  213. //We cannot just delete the .sqlite file otherwise PDO gets buggy.
  214. //SQLite is the only one with database-level optimization, instead of at table level.
  215. $this->optimize();
  216. }
  217. } else {
  218. $nbEntries = $entryDAO->countUnreadRead();
  219. if (!empty($nbEntries['all'])) {
  220. $error = 'Error: Destination database already contains some entries!';
  221. }
  222. }
  223. break;
  224. default:
  225. $error = 'Invalid copy mode!';
  226. break;
  227. }
  228. if ($error != '') {
  229. return self::stdError($error);
  230. }
  231. $sqlite = null;
  232. try {
  233. $sqlite = new Minz_PdoSqlite('sqlite:' . $filename);
  234. } catch (Exception $e) {
  235. $error = 'Error while initialising SQLite copy: ' . $e->getMessage();
  236. return self::stdError($error);
  237. }
  238. Minz_ModelPdo::clean();
  239. $userDAOSQLite = new FreshRSS_UserDAO('', $sqlite);
  240. $categoryDAOSQLite = new FreshRSS_CategoryDAOSQLite('', $sqlite);
  241. $feedDAOSQLite = new FreshRSS_FeedDAOSQLite('', $sqlite);
  242. $entryDAOSQLite = new FreshRSS_EntryDAOSQLite('', $sqlite);
  243. $tagDAOSQLite = new FreshRSS_TagDAOSQLite('', $sqlite);
  244. switch ($mode) {
  245. case self::SQLITE_EXPORT:
  246. $userFrom = $userDAO; $userTo = $userDAOSQLite;
  247. $catFrom = $catDAO; $catTo = $categoryDAOSQLite;
  248. $feedFrom = $feedDAO; $feedTo = $feedDAOSQLite;
  249. $entryFrom = $entryDAO; $entryTo = $entryDAOSQLite;
  250. $tagFrom = $tagDAO; $tagTo = $tagDAOSQLite;
  251. break;
  252. case self::SQLITE_IMPORT:
  253. $userFrom = $userDAOSQLite; $userTo = $userDAO;
  254. $catFrom = $categoryDAOSQLite; $catTo = $catDAO;
  255. $feedFrom = $feedDAOSQLite; $feedTo = $feedDAO;
  256. $entryFrom = $entryDAOSQLite; $entryTo = $entryDAO;
  257. $tagFrom = $tagDAOSQLite; $tagTo = $tagDAO;
  258. break;
  259. default:
  260. return false;
  261. }
  262. $idMaps = [];
  263. if (defined('STDERR')) {
  264. fwrite(STDERR, "Start SQL copy…\n");
  265. }
  266. $userTo->createUser();
  267. $catTo->beginTransaction();
  268. foreach ($catFrom->selectAll() as $category) {
  269. $cat = $catTo->searchByName($category['name']); //Useful for the default category
  270. if ($cat != null) {
  271. $catId = $cat->id();
  272. } else {
  273. $catId = $catTo->addCategory($category);
  274. if ($catId == false) {
  275. $error = 'Error during SQLite copy of categories!';
  276. return self::stdError($error);
  277. }
  278. }
  279. $idMaps['c' . $category['id']] = $catId;
  280. }
  281. foreach ($feedFrom->selectAll() as $feed) {
  282. $feed['category'] = empty($idMaps['c' . $feed['category']]) ? FreshRSS_CategoryDAO::DEFAULTCATEGORYID : $idMaps['c' . $feed['category']];
  283. $feedId = $feedTo->addFeed($feed);
  284. if ($feedId == false) {
  285. $error = 'Error during SQLite copy of feeds!';
  286. return self::stdError($error);
  287. }
  288. $idMaps['f' . $feed['id']] = $feedId;
  289. }
  290. $catTo->commit();
  291. $nbEntries = $entryFrom->count();
  292. $n = 0;
  293. $entryTo->beginTransaction();
  294. foreach ($entryFrom->selectAll() as $entry) {
  295. $n++;
  296. if (!empty($idMaps['f' . $entry['id_feed']])) {
  297. $entry['id_feed'] = $idMaps['f' . $entry['id_feed']];
  298. if (!$entryTo->addEntry($entry, false)) {
  299. $error = 'Error during SQLite copy of entries!';
  300. return self::stdError($error);
  301. }
  302. }
  303. if ($n % 100 === 1 && defined('STDERR')) { //Display progression
  304. fwrite(STDERR, "\033[0G" . $n . '/' . $nbEntries);
  305. }
  306. }
  307. if (defined('STDERR')) {
  308. fwrite(STDERR, "\033[0G" . $n . '/' . $nbEntries . "\n");
  309. }
  310. $entryTo->commit();
  311. $feedTo->updateCachedValues();
  312. $idMaps = [];
  313. $tagTo->beginTransaction();
  314. foreach ($tagFrom->selectAll() as $tag) {
  315. $tagId = $tagTo->addTag($tag);
  316. if ($tagId == false) {
  317. $error = 'Error during SQLite copy of tags!';
  318. return self::stdError($error);
  319. }
  320. $idMaps['t' . $tag['id']] = $tagId;
  321. }
  322. foreach ($tagFrom->selectEntryTag() as $entryTag) {
  323. if (!empty($idMaps['t' . $entryTag['id_tag']])) {
  324. $entryTag['id_tag'] = $idMaps['t' . $entryTag['id_tag']];
  325. if (!$tagTo->tagEntry($entryTag['id_tag'], $entryTag['id_entry'])) {
  326. $error = 'Error during SQLite copy of entry-tags!';
  327. return self::stdError($error);
  328. }
  329. }
  330. }
  331. $tagTo->commit();
  332. return true;
  333. }
  334. }