DatabaseDAO.php 9.5 KB

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