DatabaseDAO.php 10 KB

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