DatabaseDAO.php 9.1 KB

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