CategoryDAO.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. <?php
  2. class FreshRSS_CategoryDAO extends Minz_ModelPdo implements FreshRSS_Searchable {
  3. const DEFAULTCATEGORYID = 1;
  4. public function resetDefaultCategoryName() {
  5. //FreshRSS 1.15.1
  6. $stm = $this->pdo->prepare('UPDATE `_category` SET name = :name WHERE id = :id');
  7. if ($stm) {
  8. $stm->bindValue(':id', self::DEFAULTCATEGORYID, PDO::PARAM_INT);
  9. $stm->bindValue(':name', 'Uncategorized');
  10. }
  11. return $stm && $stm->execute();
  12. }
  13. protected function addColumn($name) {
  14. if ($this->pdo->inTransaction()) {
  15. $this->pdo->commit();
  16. }
  17. Minz_Log::warning(__method__ . ': ' . $name);
  18. try {
  19. if ($name === 'kind') { //v1.20.0
  20. return $this->pdo->exec('ALTER TABLE `_category` ADD COLUMN kind SMALLINT DEFAULT 0') !== false;
  21. } elseif ($name === 'lastUpdate') { //v1.20.0
  22. return $this->pdo->exec('ALTER TABLE `_category` ADD COLUMN `lastUpdate` BIGINT DEFAULT 0') !== false;
  23. } elseif ($name === 'error') { //v1.20.0
  24. return $this->pdo->exec('ALTER TABLE `_category` ADD COLUMN error SMALLINT DEFAULT 0') !== false;
  25. } elseif ('attributes' === $name) { //v1.15.0
  26. $ok = $this->pdo->exec('ALTER TABLE `_category` ADD COLUMN attributes TEXT') !== false;
  27. $stm = $this->pdo->query('SELECT * FROM `_feed`');
  28. $feeds = $stm->fetchAll(PDO::FETCH_ASSOC);
  29. $stm = $this->pdo->prepare('UPDATE `_feed` SET attributes = :attributes WHERE id = :id');
  30. foreach ($feeds as $feed) {
  31. if (empty($feed['keep_history']) || empty($feed['id'])) {
  32. continue;
  33. }
  34. $keepHistory = $feed['keep_history'];
  35. $attributes = empty($feed['attributes']) ? [] : json_decode($feed['attributes'], true);
  36. if (is_string($attributes)) { //Legacy risk of double-encoding
  37. $attributes = json_decode($attributes, true);
  38. }
  39. if (!is_array($attributes)) {
  40. $attributes = [];
  41. }
  42. if ($keepHistory > 0) {
  43. $attributes['archiving']['keep_min'] = intval($keepHistory);
  44. } elseif ($keepHistory == -1) { //Infinite
  45. $attributes['archiving']['keep_period'] = false;
  46. $attributes['archiving']['keep_max'] = false;
  47. $attributes['archiving']['keep_min'] = false;
  48. } else {
  49. continue;
  50. }
  51. $stm->bindValue(':id', $feed['id'], PDO::PARAM_INT);
  52. $stm->bindValue(':attributes', json_encode($attributes, JSON_UNESCAPED_SLASHES));
  53. $stm->execute();
  54. }
  55. if ($this->pdo->dbType() !== 'sqlite') { //SQLite does not support DROP COLUMN
  56. $this->pdo->exec('ALTER TABLE `_feed` DROP COLUMN keep_history');
  57. } else {
  58. $this->pdo->exec('DROP INDEX IF EXISTS feed_keep_history_index'); //SQLite at least drop index
  59. }
  60. $this->resetDefaultCategoryName();
  61. return $ok;
  62. }
  63. } catch (Exception $e) {
  64. Minz_Log::error(__method__ . ': ' . $e->getMessage());
  65. }
  66. return false;
  67. }
  68. protected function autoUpdateDb(array $errorInfo) {
  69. if (isset($errorInfo[0])) {
  70. if ($errorInfo[0] === FreshRSS_DatabaseDAO::ER_BAD_FIELD_ERROR || $errorInfo[0] === FreshRSS_DatabaseDAOPGSQL::UNDEFINED_COLUMN) {
  71. $errorLines = explode("\n", $errorInfo[2], 2); // The relevant column name is on the first line, other lines are noise
  72. foreach (['kind', 'lastUpdate', 'error', 'attributes'] as $column) {
  73. if (stripos($errorLines[0], $column) !== false) {
  74. return $this->addColumn($column);
  75. }
  76. }
  77. }
  78. }
  79. return false;
  80. }
  81. /** @return int|false */
  82. public function addCategory($valuesTmp) {
  83. // TRIM() to provide a type hint as text
  84. // No tag of the same name
  85. $sql = <<<'SQL'
  86. INSERT INTO `_category`(kind, name, attributes)
  87. SELECT * FROM (SELECT ABS(?) AS kind, TRIM(?) AS name, TRIM(?) AS attributes) c2
  88. WHERE NOT EXISTS (SELECT 1 FROM `_tag` WHERE name = TRIM(?))
  89. SQL;
  90. $stm = $this->pdo->prepare($sql);
  91. $valuesTmp['name'] = mb_strcut(trim($valuesTmp['name']), 0, FreshRSS_DatabaseDAO::LENGTH_INDEX_UNICODE, 'UTF-8');
  92. if (!isset($valuesTmp['attributes'])) {
  93. $valuesTmp['attributes'] = [];
  94. }
  95. $values = array(
  96. $valuesTmp['kind'] ?? FreshRSS_Category::KIND_NORMAL,
  97. $valuesTmp['name'],
  98. is_string($valuesTmp['attributes']) ? $valuesTmp['attributes'] : json_encode($valuesTmp['attributes'], JSON_UNESCAPED_SLASHES),
  99. $valuesTmp['name'],
  100. );
  101. if ($stm && $stm->execute($values) && $stm->rowCount() > 0) {
  102. return $this->pdo->lastInsertId('`_category_id_seq`');
  103. } else {
  104. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  105. if ($this->autoUpdateDb($info)) {
  106. return $this->addCategory($valuesTmp);
  107. }
  108. Minz_Log::error('SQL error addCategory: ' . json_encode($info));
  109. return false;
  110. }
  111. }
  112. /**
  113. * @param FreshRSS_Category $category
  114. * @return int|false
  115. */
  116. public function addCategoryObject($category) {
  117. $cat = $this->searchByName($category->name());
  118. if (!$cat) {
  119. $values = [
  120. 'kind' => $category->kind(),
  121. 'name' => $category->name(),
  122. 'attributes' => $category->attributes(),
  123. ];
  124. return $this->addCategory($values);
  125. }
  126. return $cat->id();
  127. }
  128. public function updateCategory($id, $valuesTmp) {
  129. // No tag of the same name
  130. $sql = <<<'SQL'
  131. UPDATE `_category` SET name=?, kind=?, attributes=? WHERE id=?
  132. AND NOT EXISTS (SELECT 1 FROM `_tag` WHERE name = ?)
  133. SQL;
  134. $stm = $this->pdo->prepare($sql);
  135. $valuesTmp['name'] = mb_strcut(trim($valuesTmp['name']), 0, FreshRSS_DatabaseDAO::LENGTH_INDEX_UNICODE, 'UTF-8');
  136. if (!isset($valuesTmp['attributes'])) {
  137. $valuesTmp['attributes'] = [];
  138. }
  139. $values = array(
  140. $valuesTmp['name'],
  141. $valuesTmp['kind'] ?? FreshRSS_Category::KIND_NORMAL,
  142. is_string($valuesTmp['attributes']) ? $valuesTmp['attributes'] : json_encode($valuesTmp['attributes'], JSON_UNESCAPED_SLASHES),
  143. $id,
  144. $valuesTmp['name'],
  145. );
  146. if ($stm && $stm->execute($values)) {
  147. return $stm->rowCount();
  148. } else {
  149. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  150. if ($this->autoUpdateDb($info)) {
  151. return $this->updateCategory($id, $valuesTmp);
  152. }
  153. Minz_Log::error('SQL error updateCategory: ' . json_encode($info));
  154. return false;
  155. }
  156. }
  157. public function updateLastUpdate(int $id, bool $inError = false, int $mtime = 0) {
  158. $sql = 'UPDATE `_category` SET `lastUpdate`=?, error=? WHERE id=?';
  159. $values = [
  160. $mtime <= 0 ? time() : $mtime,
  161. $inError ? 1 : 0,
  162. $id,
  163. ];
  164. $stm = $this->pdo->prepare($sql);
  165. if ($stm && $stm->execute($values)) {
  166. return $stm->rowCount();
  167. } else {
  168. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  169. Minz_Log::warning(__METHOD__ . ' error: ' . $sql . ' : ' . json_encode($info));
  170. return false;
  171. }
  172. }
  173. public function deleteCategory($id) {
  174. if ($id <= self::DEFAULTCATEGORYID) {
  175. return false;
  176. }
  177. $sql = 'DELETE FROM `_category` WHERE id=:id';
  178. $stm = $this->pdo->prepare($sql);
  179. $stm->bindParam(':id', $id, PDO::PARAM_INT);
  180. if ($stm && $stm->execute()) {
  181. return $stm->rowCount();
  182. } else {
  183. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  184. Minz_Log::error('SQL error deleteCategory: ' . json_encode($info));
  185. return false;
  186. }
  187. }
  188. public function selectAll() {
  189. $sql = 'SELECT id, name, kind, `lastUpdate`, error, attributes FROM `_category`';
  190. $stm = $this->pdo->query($sql);
  191. if ($stm != false) {
  192. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  193. yield $row;
  194. }
  195. } else {
  196. $info = $this->pdo->errorInfo();
  197. if ($this->autoUpdateDb($info)) {
  198. yield from $this->selectAll();
  199. }
  200. Minz_Log::error(__method__ . ' error: ' . json_encode($info));
  201. yield false;
  202. }
  203. }
  204. /** @return FreshRSS_Category|null */
  205. public function searchById($id) {
  206. $sql = 'SELECT * FROM `_category` WHERE id=:id';
  207. $stm = $this->pdo->prepare($sql);
  208. if ($stm &&
  209. $stm->bindParam(':id', $id, PDO::PARAM_INT) &&
  210. $stm->execute()) {
  211. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  212. $cat = self::daoToCategory($res);
  213. if (isset($cat[0])) {
  214. return $cat[0];
  215. }
  216. }
  217. return null;
  218. }
  219. /** @return FreshRSS_Category|null|false */
  220. public function searchByName(string $name) {
  221. $sql = 'SELECT * FROM `_category` WHERE name=:name';
  222. $stm = $this->pdo->prepare($sql);
  223. if ($stm == false) {
  224. return false;
  225. }
  226. $stm->bindParam(':name', $name);
  227. $stm->execute();
  228. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  229. $cat = self::daoToCategory($res);
  230. if (isset($cat[0])) {
  231. return $cat[0];
  232. } else {
  233. return null;
  234. }
  235. }
  236. public function listSortedCategories($prePopulateFeeds = true, $details = false) {
  237. $categories = $this->listCategories($prePopulateFeeds, $details);
  238. if (!is_array($categories)) {
  239. return $categories;
  240. }
  241. uasort($categories, static function ($a, $b) {
  242. $aPosition = $a->attributes('position');
  243. $bPosition = $b->attributes('position');
  244. if ($aPosition === $bPosition) {
  245. return ($a->name() < $b->name()) ? -1 : 1;
  246. } elseif (null === $aPosition) {
  247. return 1;
  248. } elseif (null === $bPosition) {
  249. return -1;
  250. }
  251. return ($aPosition < $bPosition) ? -1 : 1;
  252. });
  253. return $categories;
  254. }
  255. public function listCategories($prePopulateFeeds = true, $details = false) {
  256. if ($prePopulateFeeds) {
  257. $sql = 'SELECT c.id AS c_id, c.name AS c_name, c.kind AS c_kind, c.`lastUpdate` AS c_last_update, c.error AS c_error, c.attributes AS c_attributes, '
  258. . ($details ? 'f.* ' : 'f.id, f.name, f.url, f.website, f.priority, f.error, f.`cache_nbEntries`, f.`cache_nbUnreads`, f.ttl ')
  259. . 'FROM `_category` c '
  260. . 'LEFT OUTER JOIN `_feed` f ON f.category=c.id '
  261. . 'WHERE f.priority >= :priority_normal '
  262. . 'GROUP BY f.id, c_id '
  263. . 'ORDER BY c.name, f.name';
  264. $stm = $this->pdo->prepare($sql);
  265. $values = [ ':priority_normal' => FreshRSS_Feed::PRIORITY_NORMAL ];
  266. if ($stm && $stm->execute($values)) {
  267. return self::daoToCategoryPrepopulated($stm->fetchAll(PDO::FETCH_ASSOC));
  268. } else {
  269. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  270. if ($this->autoUpdateDb($info)) {
  271. return $this->listCategories($prePopulateFeeds, $details);
  272. }
  273. Minz_Log::error('SQL error listCategories: ' . json_encode($info));
  274. return false;
  275. }
  276. } else {
  277. $sql = 'SELECT * FROM `_category` ORDER BY name';
  278. $stm = $this->pdo->query($sql);
  279. return self::daoToCategory($stm->fetchAll(PDO::FETCH_ASSOC));
  280. }
  281. }
  282. /** @return array<FreshRSS_Category> */
  283. public function listCategoriesOrderUpdate(int $defaultCacheDuration = 86400, int $limit = 0): array {
  284. $sql = 'SELECT * FROM `_category` WHERE kind = :kind AND `lastUpdate` < :lu ORDER BY `lastUpdate`'
  285. . ($limit < 1 ? '' : ' LIMIT ' . $limit);
  286. $stm = $this->pdo->prepare($sql);
  287. if ($stm &&
  288. $stm->bindValue(':kind', FreshRSS_Category::KIND_DYNAMIC_OPML, PDO::PARAM_INT) &&
  289. $stm->bindValue(':lu', time() - $defaultCacheDuration, PDO::PARAM_INT) &&
  290. $stm->execute()) {
  291. return self::daoToCategory($stm->fetchAll(PDO::FETCH_ASSOC));
  292. } else {
  293. $info = $stm ? $stm->errorInfo() : $this->pdo->errorInfo();
  294. if ($this->autoUpdateDb($info)) {
  295. return $this->listCategoriesOrderUpdate($defaultCacheDuration, $limit);
  296. }
  297. Minz_Log::warning(__METHOD__ . ' error: ' . $sql . ' : ' . json_encode($info));
  298. return [];
  299. }
  300. }
  301. /** @return FreshRSS_Category|null */
  302. public function getDefault() {
  303. $sql = 'SELECT * FROM `_category` WHERE id=:id';
  304. $stm = $this->pdo->prepare($sql);
  305. $stm->bindValue(':id', self::DEFAULTCATEGORYID, PDO::PARAM_INT);
  306. $stm->execute();
  307. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  308. $cat = self::daoToCategory($res);
  309. if (isset($cat[0])) {
  310. return $cat[0];
  311. } else {
  312. if (FreshRSS_Context::$isCli) {
  313. fwrite(STDERR, 'FreshRSS database error: Default category not found!' . "\n");
  314. }
  315. Minz_Log::error('FreshRSS database error: Default category not found!');
  316. return null;
  317. }
  318. }
  319. /** @return int|bool */
  320. public function checkDefault() {
  321. $def_cat = $this->searchById(self::DEFAULTCATEGORYID);
  322. if ($def_cat == null) {
  323. $cat = new FreshRSS_Category(_t('gen.short.default_category'));
  324. $cat->_id(self::DEFAULTCATEGORYID);
  325. $sql = 'INSERT INTO `_category`(id, name) VALUES(?, ?)';
  326. if ($this->pdo->dbType() === 'pgsql') {
  327. //Force call to nextval()
  328. $sql .= " RETURNING nextval('`_category_id_seq`');";
  329. }
  330. $stm = $this->pdo->prepare($sql);
  331. $values = array(
  332. $cat->id(),
  333. $cat->name(),
  334. );
  335. if ($stm && $stm->execute($values)) {
  336. return $this->pdo->lastInsertId('`_category_id_seq`');
  337. } else {
  338. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  339. Minz_Log::error('SQL error check default category: ' . json_encode($info));
  340. return false;
  341. }
  342. }
  343. return true;
  344. }
  345. public function count() {
  346. $sql = 'SELECT COUNT(*) AS count FROM `_category`';
  347. $stm = $this->pdo->query($sql);
  348. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  349. return $res[0]['count'];
  350. }
  351. public function countFeed(int $id) {
  352. $sql = 'SELECT COUNT(*) AS count FROM `_feed` WHERE category=:id';
  353. $stm = $this->pdo->prepare($sql);
  354. $stm->bindParam(':id', $id, PDO::PARAM_INT);
  355. $stm->execute();
  356. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  357. return $res[0]['count'];
  358. }
  359. public function countNotRead(int $id) {
  360. $sql = 'SELECT COUNT(*) AS count FROM `_entry` e INNER JOIN `_feed` f ON e.id_feed=f.id WHERE category=:id AND e.is_read=0';
  361. $stm = $this->pdo->prepare($sql);
  362. $stm->bindParam(':id', $id, PDO::PARAM_INT);
  363. $stm->execute();
  364. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  365. return $res[0]['count'];
  366. }
  367. /**
  368. * @param array<FreshRSS_Category> $categories
  369. * @param int $feed_id
  370. */
  371. public static function findFeed(array $categories, int $feed_id) {
  372. foreach ($categories as $category) {
  373. foreach ($category->feeds() as $feed) {
  374. if ($feed->id() === $feed_id) {
  375. return $feed;
  376. }
  377. }
  378. }
  379. return null;
  380. }
  381. /**
  382. * @param array<FreshRSS_Category> $categories
  383. */
  384. public static function countUnread(array $categories, int $minPriority = 0): int {
  385. $n = 0;
  386. foreach ($categories as $category) {
  387. foreach ($category->feeds() as $feed) {
  388. if ($feed->priority() >= $minPriority) {
  389. $n += $feed->nbNotRead();
  390. }
  391. }
  392. }
  393. return $n;
  394. }
  395. public static function daoToCategoryPrepopulated($listDAO) {
  396. $list = array();
  397. if (!is_array($listDAO)) {
  398. $listDAO = array($listDAO);
  399. }
  400. $previousLine = null;
  401. $feedsDao = array();
  402. $feedDao = FreshRSS_Factory::createFeedDAO();
  403. foreach ($listDAO as $line) {
  404. if (!empty($previousLine['c_id']) && $line['c_id'] !== $previousLine['c_id']) {
  405. // End of the current category, we add it to the $list
  406. $cat = new FreshRSS_Category(
  407. $previousLine['c_name'],
  408. $feedDao->daoToFeed($feedsDao, $previousLine['c_id'])
  409. );
  410. $cat->_id($previousLine['c_id']);
  411. $cat->_kind($previousLine['c_kind']);
  412. $cat->_attributes('', $previousLine['c_attributes']);
  413. $list[$previousLine['c_id']] = $cat;
  414. $feedsDao = array(); //Prepare for next category
  415. }
  416. $previousLine = $line;
  417. $feedsDao[] = $line;
  418. }
  419. // add the last category
  420. if ($previousLine != null) {
  421. $cat = new FreshRSS_Category(
  422. $previousLine['c_name'],
  423. $feedDao->daoToFeed($feedsDao, $previousLine['c_id'])
  424. );
  425. $cat->_id($previousLine['c_id']);
  426. $cat->_kind($previousLine['c_kind']);
  427. $cat->_lastUpdate($previousLine['c_last_update'] ?? 0);
  428. $cat->_error($previousLine['c_error'] ?? false);
  429. $cat->_attributes('', $previousLine['c_attributes']);
  430. $list[$previousLine['c_id']] = $cat;
  431. }
  432. return $list;
  433. }
  434. public static function daoToCategory($listDAO) {
  435. $list = array();
  436. if (!is_array($listDAO)) {
  437. $listDAO = array($listDAO);
  438. }
  439. foreach ($listDAO as $key => $dao) {
  440. $cat = new FreshRSS_Category(
  441. $dao['name']
  442. );
  443. $cat->_id($dao['id']);
  444. $cat->_kind($dao['kind']);
  445. $cat->_lastUpdate($dao['lastUpdate'] ?? 0);
  446. $cat->_error($dao['error'] ?? false);
  447. $cat->_attributes('', isset($dao['attributes']) ? $dao['attributes'] : '');
  448. $list[$key] = $cat;
  449. }
  450. return $list;
  451. }
  452. }