DatabaseDAO.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. $catDAO = FreshRSS_Factory::createCategoryDao();
  153. $catDAO->resetDefaultCategoryName();
  154. $this->ensureCaseInsensitiveGuids();
  155. }
  156. private static function stdError($error) {
  157. if (defined('STDERR')) {
  158. fwrite(STDERR, $error . "\n");
  159. }
  160. Minz_Log::error($error);
  161. return false;
  162. }
  163. const SQLITE_EXPORT = 1;
  164. const SQLITE_IMPORT = 2;
  165. public function dbCopy($filename, $mode, $clearFirst = false) {
  166. $error = '';
  167. $userDAO = FreshRSS_Factory::createUserDao();
  168. $catDAO = FreshRSS_Factory::createCategoryDao();
  169. $feedDAO = FreshRSS_Factory::createFeedDao();
  170. $entryDAO = FreshRSS_Factory::createEntryDao();
  171. $tagDAO = FreshRSS_Factory::createTagDao();
  172. switch ($mode) {
  173. case self::SQLITE_EXPORT:
  174. if (@filesize($filename) > 0) {
  175. $error = 'Error: SQLite export file already exists: ' . $filename;
  176. }
  177. break;
  178. case self::SQLITE_IMPORT:
  179. if (!is_readable($filename)) {
  180. $error = 'Error: SQLite import file is not readable: ' . $filename;
  181. } elseif ($clearFirst) {
  182. $userDAO->deleteUser();
  183. if ($this->pdo->dbType() === 'sqlite') {
  184. //We cannot just delete the .sqlite file otherwise PDO gets buggy.
  185. //SQLite is the only one with database-level optimization, instead of at table level.
  186. $this->optimize();
  187. }
  188. } else {
  189. $nbEntries = $entryDAO->countUnreadRead();
  190. if (!empty($nbEntries['all'])) {
  191. $error = 'Error: Destination database already contains some entries!';
  192. }
  193. }
  194. break;
  195. default:
  196. $error = 'Invalid copy mode!';
  197. break;
  198. }
  199. if ($error != '') {
  200. return self::stdError($error);
  201. }
  202. $sqlite = null;
  203. try {
  204. $sqlite = new MinzPDOSQLite('sqlite:' . $filename);
  205. } catch (Exception $e) {
  206. $error = 'Error while initialising SQLite copy: ' . $e->getMessage();
  207. return self::stdError($error);
  208. }
  209. Minz_ModelPdo::clean();
  210. $userDAOSQLite = new FreshRSS_UserDAO('', $sqlite);
  211. $categoryDAOSQLite = new FreshRSS_CategoryDAOSQLite('', $sqlite);
  212. $feedDAOSQLite = new FreshRSS_FeedDAOSQLite('', $sqlite);
  213. $entryDAOSQLite = new FreshRSS_EntryDAOSQLite('', $sqlite);
  214. $tagDAOSQLite = new FreshRSS_TagDAOSQLite('', $sqlite);
  215. switch ($mode) {
  216. case self::SQLITE_EXPORT:
  217. $userFrom = $userDAO; $userTo = $userDAOSQLite;
  218. $catFrom = $catDAO; $catTo = $categoryDAOSQLite;
  219. $feedFrom = $feedDAO; $feedTo = $feedDAOSQLite;
  220. $entryFrom = $entryDAO; $entryTo = $entryDAOSQLite;
  221. $tagFrom = $tagDAO; $tagTo = $tagDAOSQLite;
  222. break;
  223. case self::SQLITE_IMPORT:
  224. $userFrom = $userDAOSQLite; $userTo = $userDAO;
  225. $catFrom = $categoryDAOSQLite; $catTo = $catDAO;
  226. $feedFrom = $feedDAOSQLite; $feedTo = $feedDAO;
  227. $entryFrom = $entryDAOSQLite; $entryTo = $entryDAO;
  228. $tagFrom = $tagDAOSQLite; $tagTo = $tagDAO;
  229. break;
  230. }
  231. $idMaps = [];
  232. if (defined('STDERR')) {
  233. fwrite(STDERR, "Start SQL copy…\n");
  234. }
  235. $userTo->createUser();
  236. $catTo->beginTransaction();
  237. foreach ($catFrom->selectAll() as $category) {
  238. $cat = $catTo->searchByName($category['name']); //Useful for the default category
  239. if ($cat != null) {
  240. $catId = $cat->id();
  241. } else {
  242. $catId = $catTo->addCategory($category);
  243. if ($catId == false) {
  244. $error = 'Error during SQLite copy of categories!';
  245. return self::stdError($error);
  246. }
  247. }
  248. $idMaps['c' . $category['id']] = $catId;
  249. }
  250. foreach ($feedFrom->selectAll() as $feed) {
  251. $feed['category'] = empty($idMaps['c' . $feed['category']]) ? FreshRSS_CategoryDAO::DEFAULTCATEGORYID : $idMaps['c' . $feed['category']];
  252. $feedId = $feedTo->addFeed($feed);
  253. if ($feedId == false) {
  254. $error = 'Error during SQLite copy of feeds!';
  255. return self::stdError($error);
  256. }
  257. $idMaps['f' . $feed['id']] = $feedId;
  258. }
  259. $catTo->commit();
  260. $nbEntries = $entryFrom->count();
  261. $n = 0;
  262. $entryTo->beginTransaction();
  263. foreach ($entryFrom->selectAll() as $entry) {
  264. $n++;
  265. if (!empty($idMaps['f' . $entry['id_feed']])) {
  266. $entry['id_feed'] = $idMaps['f' . $entry['id_feed']];
  267. if (!$entryTo->addEntry($entry, false)) {
  268. $error = 'Error during SQLite copy of entries!';
  269. return self::stdError($error);
  270. }
  271. }
  272. if ($n % 100 === 1 && defined('STDERR')) { //Display progression
  273. fwrite(STDERR, "\033[0G" . $n . '/' . $nbEntries);
  274. }
  275. }
  276. if (defined('STDERR')) {
  277. fwrite(STDERR, "\033[0G" . $n . '/' . $nbEntries . "\n");
  278. }
  279. $entryTo->commit();
  280. $feedTo->updateCachedValues();
  281. $idMaps = [];
  282. $tagTo->beginTransaction();
  283. foreach ($tagFrom->selectAll() as $tag) {
  284. $tagId = $tagTo->addTag($tag);
  285. if ($tagId == false) {
  286. $error = 'Error during SQLite copy of tags!';
  287. return self::stdError($error);
  288. }
  289. $idMaps['t' . $tag['id']] = $tagId;
  290. }
  291. foreach ($tagFrom->selectEntryTag() as $entryTag) {
  292. if (!empty($idMaps['t' . $entryTag['id_tag']])) {
  293. $entryTag['id_tag'] = $idMaps['t' . $entryTag['id_tag']];
  294. if (!$tagTo->tagEntry($entryTag['id_tag'], $entryTag['id_entry'])) {
  295. $error = 'Error during SQLite copy of entry-tags!';
  296. return self::stdError($error);
  297. }
  298. }
  299. }
  300. $tagTo->commit();
  301. return true;
  302. }
  303. }