DatabaseDAO.php 9.9 KB

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