DatabaseDAO.php 9.9 KB

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