FeedDAO.php 21 KB

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