FeedDAO.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  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): bool {
  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 true;
  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): bool {
  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. * @param bool|null $errored to include only errored feeds
  239. */
  240. public function deleteFeedByCategory(int $id, ?bool $muted = null, ?bool $errored = null): int|false {
  241. $sql = 'DELETE FROM `_feed` WHERE category=?';
  242. if ($muted) {
  243. $sql .= ' AND ttl < 0';
  244. }
  245. if ($errored) {
  246. $sql .= ' AND error <> 0';
  247. }
  248. $stm = $this->pdo->prepare($sql);
  249. $values = [$id];
  250. if ($stm !== false && $stm->execute($values)) {
  251. return $stm->rowCount();
  252. } else {
  253. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  254. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  255. return false;
  256. }
  257. }
  258. /** @return Traversable<array{'id':int,'url':string,'kind':int,'category':int,'name':string,'website':string,'description':string,'lastUpdate':int,'priority'?:int,
  259. * 'pathEntries'?:string,'httpAuth':string,'error':int|bool,'ttl'?:int,'attributes'?:string}> */
  260. public function selectAll(): Traversable {
  261. $sql = <<<'SQL'
  262. SELECT id, url, kind, category, name, website, description, `lastUpdate`,
  263. priority, `pathEntries`, `httpAuth`, error, ttl, attributes
  264. FROM `_feed`
  265. SQL;
  266. $stm = $this->pdo->query($sql);
  267. if ($stm !== false) {
  268. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  269. /** @var array{'id':int,'url':string,'kind':int,'category':int,'name':string,'website':string,'description':string,'lastUpdate':int,'priority'?:int,
  270. * 'pathEntries'?:string,'httpAuth':string,'error':int|bool,'ttl'?:int,'attributes'?:string} $row */
  271. yield $row;
  272. }
  273. } else {
  274. $info = $this->pdo->errorInfo();
  275. if ($this->autoUpdateDb($info)) {
  276. yield from $this->selectAll();
  277. } else {
  278. Minz_Log::error(__method__ . ' error: ' . json_encode($info));
  279. }
  280. }
  281. }
  282. public function searchById(int $id): ?FreshRSS_Feed {
  283. $sql = 'SELECT * FROM `_feed` WHERE id=:id';
  284. $res = $this->fetchAssoc($sql, [':id' => $id]);
  285. if ($res == null) {
  286. return null;
  287. }
  288. /** @var array<int,array{'url':string,'kind':int,'category':int,'name':string,'website':string,'lastUpdate':int,
  289. * 'priority'?:int,'pathEntries'?:string,'httpAuth':string,'error':int,'ttl'?:int,'attributes'?:string}> $res */
  290. $feeds = self::daoToFeeds($res);
  291. return $feeds[$id] ?? null;
  292. }
  293. public function searchByUrl(string $url): ?FreshRSS_Feed {
  294. $sql = 'SELECT * FROM `_feed` WHERE url=:url';
  295. $res = $this->fetchAssoc($sql, [':url' => $url]);
  296. /** @var array<int,array{'url':string,'kind':int,'category':int,'name':string,'website':string,'lastUpdate':int,
  297. * 'priority'?:int,'pathEntries'?:string,'httpAuth':string,'error':int,'ttl'?:int,'attributes'?:string}> $res */
  298. return empty($res[0]) ? null : (current(self::daoToFeeds($res)) ?: null);
  299. }
  300. /** @return array<int> */
  301. public function listFeedsIds(): array {
  302. $sql = 'SELECT id FROM `_feed`';
  303. /** @var array<int> $res */
  304. $res = $this->fetchColumn($sql, 0) ?? [];
  305. return $res;
  306. }
  307. /**
  308. * @return array<int,FreshRSS_Feed>
  309. */
  310. public function listFeeds(): array {
  311. $sql = 'SELECT * FROM `_feed` ORDER BY name';
  312. $res = $this->fetchAssoc($sql);
  313. /** @var array<array{'url':string,'kind':int,'category':int,'name':string,'website':string,'lastUpdate':int,
  314. * 'priority':int,'pathEntries':string,'httpAuth':string,'error':int,'ttl':int,'attributes':string}>|null $res */
  315. return $res == null ? [] : self::daoToFeeds($res);
  316. }
  317. /** @return array<string,string> */
  318. public function listFeedsNewestItemUsec(?int $id_feed = null): array {
  319. $sql = 'SELECT id_feed, MAX(id) as newest_item_us FROM `_entry` ';
  320. if ($id_feed === null) {
  321. $sql .= 'GROUP BY id_feed';
  322. } else {
  323. $sql .= 'WHERE id_feed=' . intval($id_feed);
  324. }
  325. $res = $this->fetchAssoc($sql);
  326. /** @var array<array{'id_feed':int,'newest_item_us':string}>|null $res */
  327. if ($res == null) {
  328. return [];
  329. }
  330. $newestItemUsec = [];
  331. foreach ($res as $line) {
  332. $newestItemUsec['f_' . $line['id_feed']] = $line['newest_item_us'];
  333. }
  334. return $newestItemUsec;
  335. }
  336. /**
  337. * @param int $defaultCacheDuration Use -1 to return all feeds, without filtering them by TTL.
  338. * @return array<int,FreshRSS_Feed>
  339. */
  340. public function listFeedsOrderUpdate(int $defaultCacheDuration = 3600, int $limit = 0): array {
  341. $sql = 'SELECT id, url, kind, category, name, website, `lastUpdate`, `pathEntries`, `httpAuth`, ttl, attributes, `cache_nbEntries`, `cache_nbUnreads` '
  342. . 'FROM `_feed` '
  343. . ($defaultCacheDuration < 0 ? '' : 'WHERE ttl >= ' . FreshRSS_Feed::TTL_DEFAULT
  344. . ' AND `lastUpdate` < (' . (time() + 60)
  345. . '-(CASE WHEN ttl=' . FreshRSS_Feed::TTL_DEFAULT . ' THEN ' . intval($defaultCacheDuration) . ' ELSE ttl END)) ')
  346. . 'ORDER BY `lastUpdate` '
  347. . ($limit < 1 ? '' : 'LIMIT ' . intval($limit));
  348. $stm = $this->pdo->query($sql);
  349. if ($stm !== false) {
  350. return self::daoToFeeds($stm->fetchAll(PDO::FETCH_ASSOC));
  351. } else {
  352. $info = $this->pdo->errorInfo();
  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 array<int,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 array<int,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>
  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 ($res == null) {
  383. return [];
  384. }
  385. /**
  386. * @var array<int,array{'url':string,'kind':int,'category':int,'name':string,'website':string,'lastUpdate':int,
  387. * 'priority'?:int,'pathEntries'?:string,'httpAuth':string,'error':int,'ttl'?:int,'attributes'?:string}> $res
  388. */
  389. $feeds = self::daoToFeeds($res);
  390. uasort($feeds, static fn(FreshRSS_Feed $a, FreshRSS_Feed $b) => strnatcasecmp($a->name(), $b->name()));
  391. return $feeds;
  392. }
  393. public function countEntries(int $id): int {
  394. $sql = 'SELECT COUNT(*) AS count FROM `_entry` WHERE id_feed=:id_feed';
  395. $res = $this->fetchColumn($sql, 0, ['id_feed' => $id]);
  396. return isset($res[0]) ? (int)($res[0]) : -1;
  397. }
  398. public function countNotRead(int $id): int {
  399. $sql = 'SELECT COUNT(*) AS count FROM `_entry` WHERE id_feed=:id_feed AND is_read=0';
  400. $res = $this->fetchColumn($sql, 0, ['id_feed' => $id]);
  401. return isset($res[0]) ? (int)($res[0]) : -1;
  402. }
  403. /**
  404. * Update cached values for selected feeds, or all feeds if no feed ID is provided.
  405. */
  406. public function updateCachedValues(int ...$feedIds): int|false {
  407. //2 sub-requests with FOREIGN KEY(e.id_feed), INDEX(e.is_read) faster than 1 request with GROUP BY or CASE
  408. $sql = <<<SQL
  409. UPDATE `_feed`
  410. SET `cache_nbEntries`=(SELECT COUNT(e1.id) FROM `_entry` e1 WHERE e1.id_feed=`_feed`.id),
  411. `cache_nbUnreads`=(SELECT COUNT(e2.id) FROM `_entry` e2 WHERE e2.id_feed=`_feed`.id AND e2.is_read=0)
  412. SQL;
  413. if (count($feedIds) > 0) {
  414. $sql .= ' WHERE id IN (' . str_repeat('?,', count($feedIds) - 1) . '?)';
  415. }
  416. $stm = $this->pdo->prepare($sql);
  417. if ($stm !== false && $stm->execute($feedIds)) {
  418. return $stm->rowCount();
  419. } else {
  420. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  421. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  422. return false;
  423. }
  424. }
  425. /**
  426. * Remember to call updateCachedValues() after calling this function
  427. * @return int|false number of lines affected or false in case of error
  428. */
  429. public function markAsReadMaxUnread(int $id, int $n): int|false {
  430. //Double SELECT for MySQL workaround ERROR 1093 (HY000)
  431. $sql = <<<'SQL'
  432. UPDATE `_entry` SET is_read=1
  433. WHERE id_feed=:id_feed1 AND is_read=0 AND id <= (SELECT e3.id FROM (
  434. SELECT e2.id FROM `_entry` e2
  435. WHERE e2.id_feed=:id_feed2 AND e2.is_read=0
  436. ORDER BY e2.id DESC
  437. LIMIT 1
  438. OFFSET :limit) e3)
  439. SQL;
  440. if (($stm = $this->pdo->prepare($sql)) !== false &&
  441. $stm->bindParam(':id_feed1', $id, PDO::PARAM_INT) &&
  442. $stm->bindParam(':id_feed2', $id, PDO::PARAM_INT) &&
  443. $stm->bindParam(':limit', $n, PDO::PARAM_INT) &&
  444. $stm->execute()) {
  445. return $stm->rowCount();
  446. } else {
  447. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  448. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  449. return false;
  450. }
  451. }
  452. /**
  453. * Remember to call updateCachedValues() after calling this function
  454. * @return int|false number of lines affected or false in case of error
  455. */
  456. public function markAsReadNotSeen(int $id, int $minLastSeen): int|false {
  457. $sql = <<<'SQL'
  458. UPDATE `_entry` SET is_read=1
  459. WHERE id_feed=:id_feed AND is_read=0 AND (`lastSeen` + 10 < :min_last_seen)
  460. SQL;
  461. if (($stm = $this->pdo->prepare($sql)) !== false &&
  462. $stm->bindValue(':id_feed', $id, PDO::PARAM_INT) &&
  463. $stm->bindValue(':min_last_seen', $minLastSeen, PDO::PARAM_INT) &&
  464. $stm->execute()) {
  465. return $stm->rowCount();
  466. } else {
  467. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  468. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  469. return false;
  470. }
  471. }
  472. public function truncate(int $id): int|false {
  473. $sql = 'DELETE FROM `_entry` WHERE id_feed=:id';
  474. $stm = $this->pdo->prepare($sql);
  475. $this->pdo->beginTransaction();
  476. if (!($stm !== false &&
  477. $stm->bindParam(':id', $id, PDO::PARAM_INT) &&
  478. $stm->execute())) {
  479. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  480. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  481. $this->pdo->rollBack();
  482. return false;
  483. }
  484. $affected = $stm->rowCount();
  485. $sql = 'UPDATE `_feed` SET `cache_nbEntries`=0, `cache_nbUnreads`=0, `lastUpdate`=0 WHERE id=:id';
  486. $stm = $this->pdo->prepare($sql);
  487. if (!($stm !== false &&
  488. $stm->bindParam(':id', $id, PDO::PARAM_INT) &&
  489. $stm->execute())) {
  490. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  491. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  492. $this->pdo->rollBack();
  493. return false;
  494. }
  495. $this->pdo->commit();
  496. return $affected;
  497. }
  498. public function purge(): bool {
  499. $sql = 'DELETE FROM `_entry`';
  500. $stm = $this->pdo->prepare($sql);
  501. $this->pdo->beginTransaction();
  502. if ($stm === false || !$stm->execute()) {
  503. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  504. Minz_Log::error('SQL error ' . __METHOD__ . ' A ' . json_encode($info));
  505. $this->pdo->rollBack();
  506. return false;
  507. }
  508. $sql = 'UPDATE `_feed` SET `cache_nbEntries` = 0, `cache_nbUnreads` = 0';
  509. $stm = $this->pdo->prepare($sql);
  510. if ($stm === false || !$stm->execute()) {
  511. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  512. Minz_Log::error('SQL error ' . __METHOD__ . ' B ' . json_encode($info));
  513. $this->pdo->rollBack();
  514. return false;
  515. }
  516. return $this->pdo->commit();
  517. }
  518. /**
  519. * @param array<int,array{'id'?:int,'url'?:string,'kind'?:int,'category'?:int,'name'?:string,'website'?:string,'description'?:string,'lastUpdate'?:int,'priority'?:int,
  520. * 'pathEntries'?:string,'httpAuth'?:string,'error'?:int|bool,'ttl'?:int,'attributes'?:string,'cache_nbUnreads'?:int,'cache_nbEntries'?:int}> $listDAO
  521. * @return array<int,FreshRSS_Feed>
  522. */
  523. public static function daoToFeeds(array $listDAO, ?int $catID = null): array {
  524. $list = [];
  525. foreach ($listDAO as $key => $dao) {
  526. FreshRSS_DatabaseDAO::pdoInt($dao, ['id', 'kind', 'category', 'lastUpdate', 'priority', 'error', 'ttl', 'cache_nbUnreads', 'cache_nbEntries']);
  527. if (!isset($dao['name'])) {
  528. continue;
  529. }
  530. if (isset($dao['id'])) {
  531. $key = (int)$dao['id'];
  532. }
  533. if ($catID === null) {
  534. $category = $dao['category'] ?? 0;
  535. } else {
  536. $category = $catID;
  537. }
  538. $myFeed = new FreshRSS_Feed($dao['url'] ?? '', false);
  539. $myFeed->_kind($dao['kind'] ?? FreshRSS_Feed::KIND_RSS);
  540. $myFeed->_categoryId($category);
  541. $myFeed->_name($dao['name']);
  542. $myFeed->_website($dao['website'] ?? '', false);
  543. $myFeed->_description($dao['description'] ?? '');
  544. $myFeed->_lastUpdate($dao['lastUpdate'] ?? 0);
  545. $myFeed->_priority($dao['priority'] ?? 10);
  546. $myFeed->_pathEntries($dao['pathEntries'] ?? '');
  547. $myFeed->_httpAuth(base64_decode($dao['httpAuth'] ?? '', true) ?: '');
  548. $myFeed->_error($dao['error'] ?? 0);
  549. $myFeed->_ttl($dao['ttl'] ?? FreshRSS_Feed::TTL_DEFAULT);
  550. $myFeed->_attributes($dao['attributes'] ?? '');
  551. $myFeed->_nbNotRead($dao['cache_nbUnreads'] ?? -1);
  552. $myFeed->_nbEntries($dao['cache_nbEntries'] ?? -1);
  553. if (isset($dao['id'])) {
  554. $myFeed->_id($dao['id']);
  555. }
  556. $list[$key] = $myFeed;
  557. }
  558. return $list;
  559. }
  560. public function count(): int {
  561. $sql = 'SELECT COUNT(e.id) AS count FROM `_feed` e';
  562. $stm = $this->pdo->query($sql);
  563. if ($stm === false) {
  564. return -1;
  565. }
  566. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  567. return (int)($res[0] ?? 0);
  568. }
  569. }