FeedDAO.php 20 KB

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