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