DatabaseDAO.php 11 KB

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