FeedDAO.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. <?php
  2. declare(strict_types=1);
  3. class FreshRSS_FeedDAO extends Minz_ModelPdo {
  4. protected function addColumn(string $name): bool {
  5. if ($this->pdo->inTransaction()) {
  6. $this->pdo->commit();
  7. }
  8. Minz_Log::warning(__method__ . ': ' . $name);
  9. try {
  10. if ($name === 'kind') { //v1.20.0
  11. return $this->pdo->exec('ALTER TABLE `_feed` ADD COLUMN kind SMALLINT DEFAULT 0') !== false;
  12. }
  13. } catch (Exception $e) {
  14. Minz_Log::error(__method__ . ' error: ' . $e->getMessage());
  15. }
  16. return false;
  17. }
  18. /** @param array<int|string> $errorInfo */
  19. protected function autoUpdateDb(array $errorInfo): bool {
  20. if (isset($errorInfo[0])) {
  21. if ($errorInfo[0] === FreshRSS_DatabaseDAO::ER_BAD_FIELD_ERROR || $errorInfo[0] === FreshRSS_DatabaseDAOPGSQL::UNDEFINED_COLUMN) {
  22. $errorLines = explode("\n", (string)$errorInfo[2], 2); // The relevant column name is on the first line, other lines are noise
  23. foreach (['kind'] as $column) {
  24. if (stripos($errorLines[0], $column) !== false) {
  25. return $this->addColumn($column);
  26. }
  27. }
  28. }
  29. }
  30. return false;
  31. }
  32. /**
  33. * @param array{'url':string,'kind':int,'category':int,'name':string,'website':string,'description':string,'lastUpdate':int,'priority'?:int,
  34. * 'pathEntries'?:string,'httpAuth':string,'error':int|bool,'ttl'?:int,'attributes'?:string|array<string|mixed>} $valuesTmp
  35. */
  36. public function addFeed(array $valuesTmp): int|false {
  37. $sql = 'INSERT INTO `_feed` (url, kind, category, name, website, description, `lastUpdate`, priority, `pathEntries`, `httpAuth`, error, ttl, attributes)
  38. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
  39. $stm = $this->pdo->prepare($sql);
  40. $valuesTmp['url'] = safe_ascii($valuesTmp['url']);
  41. $valuesTmp['website'] = safe_ascii($valuesTmp['website']);
  42. if (!isset($valuesTmp['pathEntries'])) {
  43. $valuesTmp['pathEntries'] = '';
  44. }
  45. if (!isset($valuesTmp['attributes'])) {
  46. $valuesTmp['attributes'] = [];
  47. }
  48. $values = [
  49. $valuesTmp['url'],
  50. $valuesTmp['kind'] ?? FreshRSS_Feed::KIND_RSS,
  51. $valuesTmp['category'],
  52. mb_strcut(trim($valuesTmp['name']), 0, FreshRSS_DatabaseDAO::LENGTH_INDEX_UNICODE, 'UTF-8'),
  53. $valuesTmp['website'],
  54. sanitizeHTML($valuesTmp['description'], ''),
  55. $valuesTmp['lastUpdate'],
  56. isset($valuesTmp['priority']) ? (int)$valuesTmp['priority'] : FreshRSS_Feed::PRIORITY_MAIN_STREAM,
  57. mb_strcut($valuesTmp['pathEntries'], 0, 4096, 'UTF-8'),
  58. base64_encode($valuesTmp['httpAuth']),
  59. isset($valuesTmp['error']) ? (int)$valuesTmp['error'] : 0,
  60. isset($valuesTmp['ttl']) ? (int)$valuesTmp['ttl'] : FreshRSS_Feed::TTL_DEFAULT,
  61. is_string($valuesTmp['attributes']) ? $valuesTmp['attributes'] : json_encode($valuesTmp['attributes'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
  62. ];
  63. if ($stm !== false && $stm->execute($values)) {
  64. $feedId = $this->pdo->lastInsertId('`_feed_id_seq`');
  65. return $feedId === false ? false : (int)$feedId;
  66. } else {
  67. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  68. if ($this->autoUpdateDb($info)) {
  69. return $this->addFeed($valuesTmp);
  70. }
  71. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  72. return false;
  73. }
  74. }
  75. public function addFeedObject(FreshRSS_Feed $feed): int|false {
  76. // Add feed only if we don’t find it in DB
  77. $feed_search = $this->searchByUrl($feed->url());
  78. if ($feed_search === null) {
  79. $values = [
  80. 'id' => $feed->id(),
  81. 'url' => $feed->url(),
  82. 'kind' => $feed->kind(),
  83. 'category' => $feed->categoryId(),
  84. 'name' => $feed->name(true),
  85. 'website' => $feed->website(),
  86. 'description' => $feed->description(),
  87. 'lastUpdate' => 0,
  88. 'error' => false,
  89. 'pathEntries' => $feed->pathEntries(),
  90. 'httpAuth' => $feed->httpAuth(),
  91. 'ttl' => $feed->ttl(true),
  92. 'attributes' => $feed->attributes(),
  93. ];
  94. $id = $this->addFeed($values);
  95. if ($id) {
  96. $feed->_id($id);
  97. $feed->faviconPrepare();
  98. }
  99. return $id;
  100. } else {
  101. // The feed already exists so make sure it is not muted
  102. $feed->_ttl($feed_search->ttl());
  103. $feed->_mute(false);
  104. // Merge existing and import attributes
  105. $existingAttributes = $feed_search->attributes();
  106. $importAttributes = $feed->attributes();
  107. $feed->_attributes(array_replace_recursive($existingAttributes, $importAttributes));
  108. // Update some values of the existing feed using the import
  109. $values = [
  110. 'kind' => $feed->kind(),
  111. 'name' => $feed->name(true),
  112. 'website' => $feed->website(),
  113. 'description' => $feed->description(),
  114. 'pathEntries' => $feed->pathEntries(),
  115. 'ttl' => $feed->ttl(true),
  116. 'attributes' => $feed->attributes(),
  117. ];
  118. if (!$this->updateFeed($feed_search->id(), $values)) {
  119. return false;
  120. }
  121. return $feed_search->id();
  122. }
  123. }
  124. /**
  125. * @param array{'url'?:string,'kind'?:int,'category'?:int,'name'?:string,'website'?:string,'description'?:string,'lastUpdate'?:int,'priority'?:int,
  126. * 'pathEntries'?:string,'httpAuth'?:string,'error'?:int,'ttl'?:int,'attributes'?:string|array<string,mixed>} $valuesTmp $valuesTmp
  127. */
  128. public function updateFeed(int $id, array $valuesTmp): int|false {
  129. $values = [];
  130. $originalValues = $valuesTmp;
  131. if (isset($valuesTmp['name'])) {
  132. $valuesTmp['name'] = mb_strcut(trim($valuesTmp['name']), 0, FreshRSS_DatabaseDAO::LENGTH_INDEX_UNICODE, 'UTF-8');
  133. }
  134. if (isset($valuesTmp['url'])) {
  135. $valuesTmp['url'] = safe_ascii($valuesTmp['url']);
  136. }
  137. if (isset($valuesTmp['website'])) {
  138. $valuesTmp['website'] = safe_ascii($valuesTmp['website']);
  139. }
  140. $set = '';
  141. foreach ($valuesTmp as $key => $v) {
  142. $set .= '`' . $key . '`=?, ';
  143. if ($key === 'httpAuth') {
  144. $valuesTmp[$key] = base64_encode($v);
  145. } elseif ($key === 'attributes') {
  146. $valuesTmp[$key] = is_string($valuesTmp[$key]) ? $valuesTmp[$key] : json_encode($valuesTmp[$key], JSON_UNESCAPED_SLASHES);
  147. }
  148. }
  149. $set = substr($set, 0, -2);
  150. $sql = 'UPDATE `_feed` SET ' . $set . ' WHERE id=?';
  151. $stm = $this->pdo->prepare($sql);
  152. foreach ($valuesTmp as $v) {
  153. $values[] = $v;
  154. }
  155. $values[] = $id;
  156. if ($stm !== false && $stm->execute($values)) {
  157. return $stm->rowCount();
  158. } else {
  159. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  160. if ($this->autoUpdateDb($info)) {
  161. return $this->updateFeed($id, $originalValues);
  162. }
  163. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info) . ' for feed ' . $id);
  164. return false;
  165. }
  166. }
  167. /**
  168. * @param non-empty-string $key
  169. * @param string|array<mixed>|bool|int|null $value
  170. */
  171. public function updateFeedAttribute(FreshRSS_Feed $feed, string $key, $value): int|false {
  172. $feed->_attribute($key, $value);
  173. return $this->updateFeed(
  174. $feed->id(),
  175. ['attributes' => $feed->attributes()]
  176. );
  177. }
  178. /**
  179. * @see updateCachedValues()
  180. */
  181. public function updateLastUpdate(int $id, bool $inError = false, int $mtime = 0): int|false {
  182. $sql = 'UPDATE `_feed` SET `lastUpdate`=?, error=? WHERE id=?';
  183. $values = [
  184. $mtime <= 0 ? time() : $mtime,
  185. $inError ? 1 : 0,
  186. $id,
  187. ];
  188. $stm = $this->pdo->prepare($sql);
  189. if ($stm !== false && $stm->execute($values)) {
  190. return $stm->rowCount();
  191. } else {
  192. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  193. Minz_Log::warning(__METHOD__ . ' error: ' . $sql . ' : ' . json_encode($info));
  194. return false;
  195. }
  196. }
  197. public function mute(int $id, bool $value = true): int|false {
  198. $sql = 'UPDATE `_feed` SET ttl=' . ($value ? '-' : '') . 'ABS(ttl) WHERE id=' . intval($id);
  199. return $this->pdo->exec($sql);
  200. }
  201. public function changeCategory(int $idOldCat, int $idNewCat): int|false {
  202. $catDAO = FreshRSS_Factory::createCategoryDao();
  203. $newCat = $catDAO->searchById($idNewCat);
  204. if ($newCat === null) {
  205. $newCat = $catDAO->getDefault();
  206. }
  207. if ($newCat === null) {
  208. return false;
  209. }
  210. $sql = 'UPDATE `_feed` SET category=? WHERE category=?';
  211. $stm = $this->pdo->prepare($sql);
  212. $values = [
  213. $newCat->id(),
  214. $idOldCat,
  215. ];
  216. if ($stm !== false && $stm->execute($values)) {
  217. return $stm->rowCount();
  218. } else {
  219. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  220. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  221. return false;
  222. }
  223. }
  224. public function deleteFeed(int $id): int|false {
  225. $sql = 'DELETE FROM `_feed` WHERE id=?';
  226. $stm = $this->pdo->prepare($sql);
  227. $values = [$id];
  228. if ($stm !== false && $stm->execute($values)) {
  229. return $stm->rowCount();
  230. } else {
  231. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  232. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  233. return false;
  234. }
  235. }
  236. /**
  237. * @param bool|null $muted to include only muted feeds
  238. */
  239. public function deleteFeedByCategory(int $id, ?bool $muted = null): int|false {
  240. $sql = 'DELETE FROM `_feed` WHERE category=?';
  241. if ($muted) {
  242. $sql .= ' AND ttl < 0';
  243. }
  244. $stm = $this->pdo->prepare($sql);
  245. $values = [$id];
  246. if ($stm !== false && $stm->execute($values)) {
  247. return $stm->rowCount();
  248. } else {
  249. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  250. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  251. return false;
  252. }
  253. }
  254. /** @return Traversable<array{'id':int,'url':string,'kind':int,'category':int,'name':string,'website':string,'description':string,'lastUpdate':int,'priority'?:int,
  255. * 'pathEntries'?:string,'httpAuth':string,'error':int|bool,'ttl'?:int,'attributes'?:string}> */
  256. public function selectAll(): Traversable {
  257. $sql = <<<'SQL'
  258. SELECT id, url, kind, category, name, website, description, `lastUpdate`,
  259. priority, `pathEntries`, `httpAuth`, error, ttl, attributes
  260. FROM `_feed`
  261. SQL;
  262. $stm = $this->pdo->query($sql);
  263. if ($stm !== false) {
  264. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  265. /** @var array{'id':int,'url':string,'kind':int,'category':int,'name':string,'website':string,'description':string,'lastUpdate':int,'priority'?:int,
  266. * 'pathEntries'?:string,'httpAuth':string,'error':int|bool,'ttl'?:int,'attributes'?:string} $row */
  267. yield $row;
  268. }
  269. } else {
  270. $info = $this->pdo->errorInfo();
  271. if ($this->autoUpdateDb($info)) {
  272. yield from $this->selectAll();
  273. } else {
  274. Minz_Log::error(__method__ . ' error: ' . json_encode($info));
  275. }
  276. }
  277. }
  278. public function searchById(int $id): ?FreshRSS_Feed {
  279. $sql = 'SELECT * FROM `_feed` WHERE id=:id';
  280. $res = $this->fetchAssoc($sql, [':id' => $id]);
  281. if ($res == null) {
  282. return null;
  283. }
  284. /** @var array<int,array{'url':string,'kind':int,'category':int,'name':string,'website':string,'lastUpdate':int,
  285. * 'priority'?:int,'pathEntries'?:string,'httpAuth':string,'error':int,'ttl'?:int,'attributes'?:string}> $res */
  286. $feeds = self::daoToFeeds($res);
  287. return $feeds[$id] ?? null;
  288. }
  289. public function searchByUrl(string $url): ?FreshRSS_Feed {
  290. $sql = 'SELECT * FROM `_feed` WHERE url=:url';
  291. $res = $this->fetchAssoc($sql, [':url' => $url]);
  292. /** @var array<int,array{'url':string,'kind':int,'category':int,'name':string,'website':string,'lastUpdate':int,
  293. * 'priority'?:int,'pathEntries'?:string,'httpAuth':string,'error':int,'ttl'?:int,'attributes'?:string}> $res */
  294. return empty($res[0]) ? null : (current(self::daoToFeeds($res)) ?: null);
  295. }
  296. /** @return array<int> */
  297. public function listFeedsIds(): array {
  298. $sql = 'SELECT id FROM `_feed`';
  299. /** @var array<int> $res */
  300. $res = $this->fetchColumn($sql, 0) ?? [];
  301. return $res;
  302. }
  303. /**
  304. * @return array<int,FreshRSS_Feed>
  305. */
  306. public function listFeeds(): array {
  307. $sql = 'SELECT * FROM `_feed` ORDER BY name';
  308. $res = $this->fetchAssoc($sql);
  309. /** @var array<array{'url':string,'kind':int,'category':int,'name':string,'website':string,'lastUpdate':int,
  310. * 'priority':int,'pathEntries':string,'httpAuth':string,'error':int,'ttl':int,'attributes':string}>|null $res */
  311. return $res == null ? [] : self::daoToFeeds($res);
  312. }
  313. /** @return array<string,string> */
  314. public function listFeedsNewestItemUsec(?int $id_feed = null): array {
  315. $sql = 'SELECT id_feed, MAX(id) as newest_item_us FROM `_entry` ';
  316. if ($id_feed === null) {
  317. $sql .= 'GROUP BY id_feed';
  318. } else {
  319. $sql .= 'WHERE id_feed=' . intval($id_feed);
  320. }
  321. $res = $this->fetchAssoc($sql);
  322. /** @var array<array{'id_feed':int,'newest_item_us':string}>|null $res */
  323. if ($res == null) {
  324. return [];
  325. }
  326. $newestItemUsec = [];
  327. foreach ($res as $line) {
  328. $newestItemUsec['f_' . $line['id_feed']] = $line['newest_item_us'];
  329. }
  330. return $newestItemUsec;
  331. }
  332. /**
  333. * @param int $defaultCacheDuration Use -1 to return all feeds, without filtering them by TTL.
  334. * @return array<int,FreshRSS_Feed>
  335. */
  336. public function listFeedsOrderUpdate(int $defaultCacheDuration = 3600, int $limit = 0): array {
  337. $sql = 'SELECT id, url, kind, category, name, website, `lastUpdate`, `pathEntries`, `httpAuth`, ttl, attributes, `cache_nbEntries`, `cache_nbUnreads` '
  338. . 'FROM `_feed` '
  339. . ($defaultCacheDuration < 0 ? '' : 'WHERE ttl >= ' . FreshRSS_Feed::TTL_DEFAULT
  340. . ' AND `lastUpdate` < (' . (time() + 60)
  341. . '-(CASE WHEN ttl=' . FreshRSS_Feed::TTL_DEFAULT . ' THEN ' . intval($defaultCacheDuration) . ' ELSE ttl END)) ')
  342. . 'ORDER BY `lastUpdate` '
  343. . ($limit < 1 ? '' : 'LIMIT ' . intval($limit));
  344. $stm = $this->pdo->query($sql);
  345. if ($stm !== false) {
  346. return self::daoToFeeds($stm->fetchAll(PDO::FETCH_ASSOC));
  347. } else {
  348. $info = $this->pdo->errorInfo();
  349. if ($this->autoUpdateDb($info)) {
  350. return $this->listFeedsOrderUpdate($defaultCacheDuration, $limit);
  351. }
  352. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  353. return [];
  354. }
  355. }
  356. /** @return array<int,string> */
  357. public function listTitles(int $id, int $limit = 0): array {
  358. $sql = 'SELECT title FROM `_entry` WHERE id_feed=:id_feed ORDER BY id DESC'
  359. . ($limit < 1 ? '' : ' LIMIT ' . intval($limit));
  360. $res = $this->fetchColumn($sql, 0, [':id_feed' => $id]) ?? [];
  361. /** @var array<int,string> $res */
  362. return $res;
  363. }
  364. /**
  365. * @param bool|null $muted to include only muted feeds
  366. * @return array<int,FreshRSS_Feed>
  367. */
  368. public function listByCategory(int $cat, ?bool $muted = null): array {
  369. $sql = 'SELECT * FROM `_feed` WHERE category=:category';
  370. if ($muted) {
  371. $sql .= ' AND ttl < 0';
  372. }
  373. $res = $this->fetchAssoc($sql, [':category' => $cat]);
  374. if ($res == null) {
  375. return [];
  376. }
  377. /**
  378. * @var array<int,array{'url':string,'kind':int,'category':int,'name':string,'website':string,'lastUpdate':int,
  379. * 'priority'?:int,'pathEntries'?:string,'httpAuth':string,'error':int,'ttl'?:int,'attributes'?:string}> $res
  380. */
  381. $feeds = self::daoToFeeds($res);
  382. uasort($feeds, static function (FreshRSS_Feed $a, FreshRSS_Feed $b) {
  383. return strnatcasecmp($a->name(), $b->name());
  384. });
  385. return $feeds;
  386. }
  387. public function countEntries(int $id): int {
  388. $sql = 'SELECT COUNT(*) AS count FROM `_entry` WHERE id_feed=:id_feed';
  389. $res = $this->fetchColumn($sql, 0, ['id_feed' => $id]);
  390. return isset($res[0]) ? (int)($res[0]) : -1;
  391. }
  392. public function countNotRead(int $id): int {
  393. $sql = 'SELECT COUNT(*) AS count FROM `_entry` WHERE id_feed=:id_feed AND is_read=0';
  394. $res = $this->fetchColumn($sql, 0, ['id_feed' => $id]);
  395. return isset($res[0]) ? (int)($res[0]) : -1;
  396. }
  397. /**
  398. * Update cached values for selected feeds, or all feeds if no feed ID is provided.
  399. */
  400. public function updateCachedValues(int ...$feedIds): int|false {
  401. //2 sub-requests with FOREIGN KEY(e.id_feed), INDEX(e.is_read) faster than 1 request with GROUP BY or CASE
  402. $sql = <<<SQL
  403. UPDATE `_feed`
  404. SET `cache_nbEntries`=(SELECT COUNT(e1.id) FROM `_entry` e1 WHERE e1.id_feed=`_feed`.id),
  405. `cache_nbUnreads`=(SELECT COUNT(e2.id) FROM `_entry` e2 WHERE e2.id_feed=`_feed`.id AND e2.is_read=0)
  406. SQL;
  407. if (count($feedIds) > 0) {
  408. $sql .= ' WHERE id IN (' . str_repeat('?,', count($feedIds) - 1) . '?)';
  409. }
  410. $stm = $this->pdo->prepare($sql);
  411. if ($stm !== false && $stm->execute($feedIds)) {
  412. return $stm->rowCount();
  413. } else {
  414. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  415. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  416. return false;
  417. }
  418. }
  419. /**
  420. * Remember to call updateCachedValues() after calling this function
  421. * @return int|false number of lines affected or false in case of error
  422. */
  423. public function markAsReadMaxUnread(int $id, int $n): int|false {
  424. //Double SELECT for MySQL workaround ERROR 1093 (HY000)
  425. $sql = <<<'SQL'
  426. UPDATE `_entry` SET is_read=1
  427. WHERE id_feed=:id_feed1 AND is_read=0 AND id <= (SELECT e3.id FROM (
  428. SELECT e2.id FROM `_entry` e2
  429. WHERE e2.id_feed=:id_feed2 AND e2.is_read=0
  430. ORDER BY e2.id DESC
  431. LIMIT 1
  432. OFFSET :limit) e3)
  433. SQL;
  434. if (($stm = $this->pdo->prepare($sql)) !== false &&
  435. $stm->bindParam(':id_feed1', $id, PDO::PARAM_INT) &&
  436. $stm->bindParam(':id_feed2', $id, PDO::PARAM_INT) &&
  437. $stm->bindParam(':limit', $n, PDO::PARAM_INT) &&
  438. $stm->execute()) {
  439. return $stm->rowCount();
  440. } else {
  441. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  442. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  443. return false;
  444. }
  445. }
  446. /**
  447. * Remember to call updateCachedValues() after calling this function
  448. * @return int|false number of lines affected or false in case of error
  449. */
  450. public function markAsReadNotSeen(int $id, int $minLastSeen): int|false {
  451. $sql = <<<'SQL'
  452. UPDATE `_entry` SET is_read=1
  453. WHERE id_feed=:id_feed AND is_read=0 AND (`lastSeen` + 10 < :min_last_seen)
  454. SQL;
  455. if (($stm = $this->pdo->prepare($sql)) !== false &&
  456. $stm->bindValue(':id_feed', $id, PDO::PARAM_INT) &&
  457. $stm->bindValue(':min_last_seen', $minLastSeen, PDO::PARAM_INT) &&
  458. $stm->execute()) {
  459. return $stm->rowCount();
  460. } else {
  461. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  462. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  463. return false;
  464. }
  465. }
  466. public function truncate(int $id): int|false {
  467. $sql = 'DELETE FROM `_entry` WHERE id_feed=:id';
  468. $stm = $this->pdo->prepare($sql);
  469. $this->pdo->beginTransaction();
  470. if (!($stm !== false &&
  471. $stm->bindParam(':id', $id, PDO::PARAM_INT) &&
  472. $stm->execute())) {
  473. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  474. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  475. $this->pdo->rollBack();
  476. return false;
  477. }
  478. $affected = $stm->rowCount();
  479. $sql = 'UPDATE `_feed` SET `cache_nbEntries`=0, `cache_nbUnreads`=0, `lastUpdate`=0 WHERE id=:id';
  480. $stm = $this->pdo->prepare($sql);
  481. if (!($stm !== false &&
  482. $stm->bindParam(':id', $id, PDO::PARAM_INT) &&
  483. $stm->execute())) {
  484. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  485. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  486. $this->pdo->rollBack();
  487. return false;
  488. }
  489. $this->pdo->commit();
  490. return $affected;
  491. }
  492. public function purge(): bool {
  493. $sql = 'DELETE FROM `_entry`';
  494. $stm = $this->pdo->prepare($sql);
  495. $this->pdo->beginTransaction();
  496. if ($stm === false || !$stm->execute()) {
  497. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  498. Minz_Log::error('SQL error ' . __METHOD__ . ' A ' . json_encode($info));
  499. $this->pdo->rollBack();
  500. return false;
  501. }
  502. $sql = 'UPDATE `_feed` SET `cache_nbEntries` = 0, `cache_nbUnreads` = 0';
  503. $stm = $this->pdo->prepare($sql);
  504. if ($stm === false || !$stm->execute()) {
  505. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  506. Minz_Log::error('SQL error ' . __METHOD__ . ' B ' . json_encode($info));
  507. $this->pdo->rollBack();
  508. return false;
  509. }
  510. return $this->pdo->commit();
  511. }
  512. /**
  513. * @param array<int,array{'id'?:int,'url'?:string,'kind'?:int,'category'?:int,'name'?:string,'website'?:string,'description'?:string,'lastUpdate'?:int,'priority'?:int,
  514. * 'pathEntries'?:string,'httpAuth'?:string,'error'?:int|bool,'ttl'?:int,'attributes'?:string,'cache_nbUnreads'?:int,'cache_nbEntries'?:int}> $listDAO
  515. * @return array<int,FreshRSS_Feed>
  516. */
  517. public static function daoToFeeds(array $listDAO, ?int $catID = null): array {
  518. $list = [];
  519. foreach ($listDAO as $key => $dao) {
  520. FreshRSS_DatabaseDAO::pdoInt($dao, ['id', 'kind', 'category', 'lastUpdate', 'priority', 'error', 'ttl', 'cache_nbUnreads', 'cache_nbEntries']);
  521. if (!isset($dao['name'])) {
  522. continue;
  523. }
  524. if (isset($dao['id'])) {
  525. $key = (int)$dao['id'];
  526. }
  527. if ($catID === null) {
  528. $category = $dao['category'] ?? 0;
  529. } else {
  530. $category = $catID;
  531. }
  532. $myFeed = new FreshRSS_Feed($dao['url'] ?? '', false);
  533. $myFeed->_kind($dao['kind'] ?? FreshRSS_Feed::KIND_RSS);
  534. $myFeed->_categoryId($category);
  535. $myFeed->_name($dao['name']);
  536. $myFeed->_website($dao['website'] ?? '', false);
  537. $myFeed->_description($dao['description'] ?? '');
  538. $myFeed->_lastUpdate($dao['lastUpdate'] ?? 0);
  539. $myFeed->_priority($dao['priority'] ?? 10);
  540. $myFeed->_pathEntries($dao['pathEntries'] ?? '');
  541. $myFeed->_httpAuth(base64_decode($dao['httpAuth'] ?? '', true) ?: '');
  542. $myFeed->_error($dao['error'] ?? 0);
  543. $myFeed->_ttl($dao['ttl'] ?? FreshRSS_Feed::TTL_DEFAULT);
  544. $myFeed->_attributes($dao['attributes'] ?? '');
  545. $myFeed->_nbNotRead($dao['cache_nbUnreads'] ?? -1);
  546. $myFeed->_nbEntries($dao['cache_nbEntries'] ?? -1);
  547. if (isset($dao['id'])) {
  548. $myFeed->_id($dao['id']);
  549. }
  550. $list[$key] = $myFeed;
  551. }
  552. return $list;
  553. }
  554. public function count(): int {
  555. $sql = 'SELECT COUNT(e.id) AS count FROM `_feed` e';
  556. $stm = $this->pdo->query($sql);
  557. if ($stm === false) {
  558. return -1;
  559. }
  560. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  561. return (int)($res[0] ?? 0);
  562. }
  563. }