FeedDAO.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  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. */
  37. public function addFeed(array $valuesTmp) {
  38. $sql = 'INSERT INTO `_feed` (url, kind, category, name, website, description, `lastUpdate`, priority, `pathEntries`, `httpAuth`, error, ttl, attributes)
  39. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
  40. $stm = $this->pdo->prepare($sql);
  41. $valuesTmp['url'] = safe_ascii($valuesTmp['url']);
  42. $valuesTmp['website'] = safe_ascii($valuesTmp['website']);
  43. if (!isset($valuesTmp['pathEntries'])) {
  44. $valuesTmp['pathEntries'] = '';
  45. }
  46. if (!isset($valuesTmp['attributes'])) {
  47. $valuesTmp['attributes'] = [];
  48. }
  49. $values = [
  50. $valuesTmp['url'],
  51. $valuesTmp['kind'] ?? FreshRSS_Feed::KIND_RSS,
  52. $valuesTmp['category'],
  53. mb_strcut(trim($valuesTmp['name']), 0, FreshRSS_DatabaseDAO::LENGTH_INDEX_UNICODE, 'UTF-8'),
  54. $valuesTmp['website'],
  55. sanitizeHTML($valuesTmp['description'], ''),
  56. $valuesTmp['lastUpdate'],
  57. isset($valuesTmp['priority']) ? (int)$valuesTmp['priority'] : FreshRSS_Feed::PRIORITY_MAIN_STREAM,
  58. mb_strcut($valuesTmp['pathEntries'], 0, 4096, 'UTF-8'),
  59. base64_encode($valuesTmp['httpAuth']),
  60. isset($valuesTmp['error']) ? (int)$valuesTmp['error'] : 0,
  61. isset($valuesTmp['ttl']) ? (int)$valuesTmp['ttl'] : FreshRSS_Feed::TTL_DEFAULT,
  62. is_string($valuesTmp['attributes']) ? $valuesTmp['attributes'] : json_encode($valuesTmp['attributes'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
  63. ];
  64. if ($stm !== false && $stm->execute($values)) {
  65. $feedId = $this->pdo->lastInsertId('`_feed_id_seq`');
  66. return $feedId === false ? false : (int)$feedId;
  67. } else {
  68. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  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. /** @return int|false */
  77. public function addFeedObject(FreshRSS_Feed $feed) {
  78. // Add feed only if we don’t find it in DB
  79. $feed_search = $this->searchByUrl($feed->url());
  80. if (!$feed_search) {
  81. $values = [
  82. 'id' => $feed->id(),
  83. 'url' => $feed->url(),
  84. 'kind' => $feed->kind(),
  85. 'category' => $feed->categoryId(),
  86. 'name' => $feed->name(true),
  87. 'website' => $feed->website(),
  88. 'description' => $feed->description(),
  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. * @return int|false
  130. */
  131. public function updateFeed(int $id, array $valuesTmp) {
  132. $values = [];
  133. $originalValues = $valuesTmp;
  134. if (isset($valuesTmp['name'])) {
  135. $valuesTmp['name'] = mb_strcut(trim($valuesTmp['name']), 0, FreshRSS_DatabaseDAO::LENGTH_INDEX_UNICODE, 'UTF-8');
  136. }
  137. if (isset($valuesTmp['url'])) {
  138. $valuesTmp['url'] = safe_ascii($valuesTmp['url']);
  139. }
  140. if (isset($valuesTmp['website'])) {
  141. $valuesTmp['website'] = safe_ascii($valuesTmp['website']);
  142. }
  143. $set = '';
  144. foreach ($valuesTmp as $key => $v) {
  145. $set .= '`' . $key . '`=?, ';
  146. if ($key === 'httpAuth') {
  147. $valuesTmp[$key] = base64_encode($v);
  148. } elseif ($key === 'attributes') {
  149. $valuesTmp[$key] = is_string($valuesTmp[$key]) ? $valuesTmp[$key] : json_encode($valuesTmp[$key], JSON_UNESCAPED_SLASHES);
  150. }
  151. }
  152. $set = substr($set, 0, -2);
  153. $sql = 'UPDATE `_feed` SET ' . $set . ' WHERE id=?';
  154. $stm = $this->pdo->prepare($sql);
  155. foreach ($valuesTmp as $v) {
  156. $values[] = $v;
  157. }
  158. $values[] = $id;
  159. if ($stm !== false && $stm->execute($values)) {
  160. return $stm->rowCount();
  161. } else {
  162. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  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. * @return int|false
  174. */
  175. public function updateFeedAttribute(FreshRSS_Feed $feed, string $key, $value) {
  176. $feed->_attribute($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. if ($newCat === null) {
  215. return false;
  216. }
  217. $sql = 'UPDATE `_feed` SET category=? WHERE category=?';
  218. $stm = $this->pdo->prepare($sql);
  219. $values = [
  220. $newCat->id(),
  221. $idOldCat,
  222. ];
  223. if ($stm !== false && $stm->execute($values)) {
  224. return $stm->rowCount();
  225. } else {
  226. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  227. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  228. return false;
  229. }
  230. }
  231. /** @return int|false */
  232. public function deleteFeed(int $id) {
  233. $sql = 'DELETE FROM `_feed` WHERE id=?';
  234. $stm = $this->pdo->prepare($sql);
  235. $values = [$id];
  236. if ($stm !== false && $stm->execute($values)) {
  237. return $stm->rowCount();
  238. } else {
  239. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  240. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  241. return false;
  242. }
  243. }
  244. /**
  245. * @param bool|null $muted to include only muted feeds
  246. * @return int|false
  247. */
  248. public function deleteFeedByCategory(int $id, ?bool $muted = null) {
  249. $sql = 'DELETE FROM `_feed` WHERE category=?';
  250. if ($muted) {
  251. $sql .= ' AND ttl < 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 == null ? $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. return;
  274. }
  275. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  276. /** @var array{'id':int,'url':string,'kind':int,'category':int,'name':string,'website':string,'description':string,'lastUpdate':int,'priority'?:int,
  277. * 'pathEntries'?:string,'httpAuth':string,'error':int|bool,'ttl'?:int,'attributes'?:string} $row */
  278. yield $row;
  279. }
  280. }
  281. public function searchById(int $id): ?FreshRSS_Feed {
  282. $sql = 'SELECT * FROM `_feed` WHERE id=:id';
  283. $res = $this->fetchAssoc($sql, [':id' => $id]);
  284. if ($res == null) {
  285. return null;
  286. }
  287. /** @var array<int,array{'url':string,'kind':int,'category':int,'name':string,'website':string,'lastUpdate':int,
  288. * 'priority'?:int,'pathEntries'?:string,'httpAuth':string,'error':int,'ttl'?:int,'attributes'?:string}> $res */
  289. $feeds = self::daoToFeeds($res);
  290. return $feeds[$id] ?? null;
  291. }
  292. public function searchByUrl(string $url): ?FreshRSS_Feed {
  293. $sql = 'SELECT * FROM `_feed` WHERE url=:url';
  294. $res = $this->fetchAssoc($sql, [':url' => $url]);
  295. /** @var array<int,array{'url':string,'kind':int,'category':int,'name':string,'website':string,'lastUpdate':int,
  296. * 'priority'?:int,'pathEntries'?:string,'httpAuth':string,'error':int,'ttl'?:int,'attributes'?:string}> $res */
  297. return empty($res[0]) ? null : (current(self::daoToFeeds($res)) ?: null);
  298. }
  299. /** @return array<int> */
  300. public function listFeedsIds(): array {
  301. $sql = 'SELECT id FROM `_feed`';
  302. /** @var array<int> $res */
  303. $res = $this->fetchColumn($sql, 0) ?? [];
  304. return $res;
  305. }
  306. /**
  307. * @return array<int,FreshRSS_Feed>
  308. */
  309. public function listFeeds(): array {
  310. $sql = 'SELECT * FROM `_feed` ORDER BY name';
  311. $res = $this->fetchAssoc($sql);
  312. /** @var array<array{'url':string,'kind':int,'category':int,'name':string,'website':string,'lastUpdate':int,
  313. * 'priority':int,'pathEntries':string,'httpAuth':string,'error':int,'ttl':int,'attributes':string}>|null $res */
  314. return $res == null ? [] : self::daoToFeeds($res);
  315. }
  316. /** @return array<string,string> */
  317. public function listFeedsNewestItemUsec(?int $id_feed = null): array {
  318. $sql = 'SELECT id_feed, MAX(id) as newest_item_us FROM `_entry` ';
  319. if ($id_feed === null) {
  320. $sql .= 'GROUP BY id_feed';
  321. } else {
  322. $sql .= 'WHERE id_feed=' . intval($id_feed);
  323. }
  324. $res = $this->fetchAssoc($sql);
  325. /** @var array<array{'id_feed':int,'newest_item_us':string}>|null $res */
  326. if ($res == null) {
  327. return [];
  328. }
  329. $newestItemUsec = [];
  330. foreach ($res as $line) {
  331. $newestItemUsec['f_' . $line['id_feed']] = $line['newest_item_us'];
  332. }
  333. return $newestItemUsec;
  334. }
  335. /**
  336. * @param int $defaultCacheDuration Use -1 to return all feeds, without filtering them by TTL.
  337. * @return array<int,FreshRSS_Feed>
  338. */
  339. public function listFeedsOrderUpdate(int $defaultCacheDuration = 3600, int $limit = 0): array {
  340. $sql = 'SELECT id, url, kind, category, name, website, `lastUpdate`, `pathEntries`, `httpAuth`, ttl, attributes, `cache_nbEntries`, `cache_nbUnreads` '
  341. . 'FROM `_feed` '
  342. . ($defaultCacheDuration < 0 ? '' : 'WHERE ttl >= ' . FreshRSS_Feed::TTL_DEFAULT
  343. . ' AND `lastUpdate` < (' . (time() + 60)
  344. . '-(CASE WHEN ttl=' . FreshRSS_Feed::TTL_DEFAULT . ' THEN ' . intval($defaultCacheDuration) . ' ELSE ttl END)) ')
  345. . 'ORDER BY `lastUpdate` '
  346. . ($limit < 1 ? '' : 'LIMIT ' . intval($limit));
  347. $stm = $this->pdo->query($sql);
  348. if ($stm !== false) {
  349. return self::daoToFeeds($stm->fetchAll(PDO::FETCH_ASSOC));
  350. } else {
  351. $info = $this->pdo->errorInfo();
  352. if ($this->autoUpdateDb($info)) {
  353. return $this->listFeedsOrderUpdate($defaultCacheDuration, $limit);
  354. }
  355. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  356. return [];
  357. }
  358. }
  359. /** @return array<int,string> */
  360. public function listTitles(int $id, int $limit = 0): array {
  361. $sql = 'SELECT title FROM `_entry` WHERE id_feed=:id_feed ORDER BY id DESC'
  362. . ($limit < 1 ? '' : ' LIMIT ' . intval($limit));
  363. $res = $this->fetchColumn($sql, 0, [':id_feed' => $id]) ?? [];
  364. /** @var array<int,string> $res */
  365. return $res;
  366. }
  367. /**
  368. * @param bool|null $muted to include only muted feeds
  369. * @return array<int,FreshRSS_Feed>
  370. */
  371. public function listByCategory(int $cat, ?bool $muted = null): array {
  372. $sql = 'SELECT * FROM `_feed` WHERE category=:category';
  373. if ($muted) {
  374. $sql .= ' AND ttl < 0';
  375. }
  376. $res = $this->fetchAssoc($sql, [':category' => $cat]);
  377. if ($res == null) {
  378. return [];
  379. }
  380. /**
  381. * @var array<int,array{'url':string,'kind':int,'category':int,'name':string,'website':string,'lastUpdate':int,
  382. * 'priority'?:int,'pathEntries'?:string,'httpAuth':string,'error':int,'ttl'?:int,'attributes'?:string}> $res
  383. */
  384. $feeds = self::daoToFeeds($res);
  385. uasort($feeds, static function (FreshRSS_Feed $a, FreshRSS_Feed $b) {
  386. return strnatcasecmp($a->name(), $b->name());
  387. });
  388. return $feeds;
  389. }
  390. public function countEntries(int $id): int {
  391. $sql = 'SELECT COUNT(*) AS count FROM `_entry` WHERE id_feed=:id_feed';
  392. $res = $this->fetchColumn($sql, 0, ['id_feed' => $id]);
  393. return isset($res[0]) ? (int)($res[0]) : -1;
  394. }
  395. public function countNotRead(int $id): int {
  396. $sql = 'SELECT COUNT(*) AS count FROM `_entry` WHERE id_feed=:id_feed AND is_read=0';
  397. $res = $this->fetchColumn($sql, 0, ['id_feed' => $id]);
  398. return isset($res[0]) ? (int)($res[0]) : -1;
  399. }
  400. /**
  401. * @return int|false
  402. */
  403. public function updateCachedValues(int $id = 0) {
  404. //2 sub-requests with FOREIGN KEY(e.id_feed), INDEX(e.is_read) faster than 1 request with GROUP BY or CASE
  405. $sql = '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. . ($id != 0 ? ' WHERE id=:id' : '');
  409. $stm = $this->pdo->prepare($sql);
  410. if ($stm !== false && $id != 0) {
  411. $stm->bindParam(':id', $id, PDO::PARAM_INT);
  412. }
  413. if ($stm !== false && $stm->execute()) {
  414. return $stm->rowCount();
  415. } else {
  416. $info = $stm == null ? $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) {
  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)) &&
  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 == null ? $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 markAsReadUponGone(int $id) {
  453. //Double SELECT for MySQL workaround ERROR 1093 (HY000)
  454. $sql = <<<'SQL'
  455. UPDATE `_entry` SET is_read=1
  456. WHERE id_feed=:id_feed1 AND is_read=0 AND (
  457. `lastSeen` + 60 < (SELECT s1.maxlastseen FROM (
  458. SELECT MAX(e2.`lastSeen`) AS maxlastseen FROM `_entry` e2 WHERE e2.id_feed = :id_feed2
  459. ) s1)
  460. )
  461. SQL;
  462. if (($stm = $this->pdo->prepare($sql)) &&
  463. $stm->bindParam(':id_feed1', $id, PDO::PARAM_INT) &&
  464. $stm->bindParam(':id_feed2', $id, PDO::PARAM_INT) &&
  465. $stm->execute()) {
  466. return $stm->rowCount();
  467. } else {
  468. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  469. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  470. return false;
  471. }
  472. }
  473. /**
  474. * @return int|false
  475. */
  476. public function truncate(int $id) {
  477. $sql = 'DELETE FROM `_entry` WHERE id_feed=:id';
  478. $stm = $this->pdo->prepare($sql);
  479. $this->pdo->beginTransaction();
  480. if (!($stm !== false &&
  481. $stm->bindParam(':id', $id, PDO::PARAM_INT) &&
  482. $stm->execute())) {
  483. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  484. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  485. $this->pdo->rollBack();
  486. return false;
  487. }
  488. $affected = $stm->rowCount();
  489. $sql = 'UPDATE `_feed` SET `cache_nbEntries`=0, `cache_nbUnreads`=0, `lastUpdate`=0 WHERE id=:id';
  490. $stm = $this->pdo->prepare($sql);
  491. if (!($stm !== false &&
  492. $stm->bindParam(':id', $id, PDO::PARAM_INT) &&
  493. $stm->execute())) {
  494. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  495. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  496. $this->pdo->rollBack();
  497. return false;
  498. }
  499. $this->pdo->commit();
  500. return $affected;
  501. }
  502. public function purge(): bool {
  503. $sql = 'DELETE FROM `_entry`';
  504. $stm = $this->pdo->prepare($sql);
  505. $this->pdo->beginTransaction();
  506. if (!($stm && $stm->execute())) {
  507. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  508. Minz_Log::error('SQL error ' . __METHOD__ . ' A ' . json_encode($info));
  509. $this->pdo->rollBack();
  510. return false;
  511. }
  512. $sql = 'UPDATE `_feed` SET `cache_nbEntries` = 0, `cache_nbUnreads` = 0';
  513. $stm = $this->pdo->prepare($sql);
  514. if (!($stm && $stm->execute())) {
  515. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  516. Minz_Log::error('SQL error ' . __METHOD__ . ' B ' . json_encode($info));
  517. $this->pdo->rollBack();
  518. return false;
  519. }
  520. return $this->pdo->commit();
  521. }
  522. /**
  523. * @param array<int,array{'id'?:int,'url'?:string,'kind'?:int,'category'?:int,'name'?:string,'website'?:string,'description'?:string,'lastUpdate'?:int,'priority'?:int,
  524. * 'pathEntries'?:string,'httpAuth'?:string,'error'?:int|bool,'ttl'?:int,'attributes'?:string,'cache_nbUnreads'?:int,'cache_nbEntries'?:int}> $listDAO
  525. * @return array<int,FreshRSS_Feed>
  526. */
  527. public static function daoToFeeds(array $listDAO, ?int $catID = null): array {
  528. $list = [];
  529. foreach ($listDAO as $key => $dao) {
  530. FreshRSS_DatabaseDAO::pdoInt($dao, ['id', 'kind', 'category', 'lastUpdate', 'priority', 'error', 'ttl', 'cache_nbUnreads', 'cache_nbEntries']);
  531. if (!isset($dao['name'])) {
  532. continue;
  533. }
  534. if (isset($dao['id'])) {
  535. $key = (int)$dao['id'];
  536. }
  537. if ($catID === null) {
  538. $category = $dao['category'] ?? 0;
  539. } else {
  540. $category = $catID;
  541. }
  542. $myFeed = new FreshRSS_Feed($dao['url'] ?? '', false);
  543. $myFeed->_kind($dao['kind'] ?? FreshRSS_Feed::KIND_RSS);
  544. $myFeed->_categoryId($category);
  545. $myFeed->_name($dao['name']);
  546. $myFeed->_website($dao['website'] ?? '', false);
  547. $myFeed->_description($dao['description'] ?? '');
  548. $myFeed->_lastUpdate($dao['lastUpdate'] ?? 0);
  549. $myFeed->_priority($dao['priority'] ?? 10);
  550. $myFeed->_pathEntries($dao['pathEntries'] ?? '');
  551. $myFeed->_httpAuth(base64_decode($dao['httpAuth'] ?? '', true) ?: '');
  552. $myFeed->_error($dao['error'] ?? 0);
  553. $myFeed->_ttl($dao['ttl'] ?? FreshRSS_Feed::TTL_DEFAULT);
  554. $myFeed->_attributes($dao['attributes'] ?? '');
  555. $myFeed->_nbNotRead($dao['cache_nbUnreads'] ?? -1);
  556. $myFeed->_nbEntries($dao['cache_nbEntries'] ?? -1);
  557. if (isset($dao['id'])) {
  558. $myFeed->_id($dao['id']);
  559. }
  560. $list[$key] = $myFeed;
  561. }
  562. return $list;
  563. }
  564. public function count(): int {
  565. $sql = 'SELECT COUNT(e.id) AS count FROM `_feed` e';
  566. $stm = $this->pdo->query($sql);
  567. if ($stm == false) {
  568. return -1;
  569. }
  570. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  571. return (int)($res[0] ?? 0);
  572. }
  573. }