FeedDAO.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. <?php
  2. class FreshRSS_FeedDAO extends Minz_ModelPdo {
  3. protected function addColumn(string $name): bool {
  4. if ($this->pdo->inTransaction()) {
  5. $this->pdo->commit();
  6. }
  7. Minz_Log::warning(__method__ . ': ' . $name);
  8. try {
  9. if ($name === 'kind') { //v1.20.0
  10. return $this->pdo->exec('ALTER TABLE `_feed` ADD COLUMN kind SMALLINT DEFAULT 0') !== false;
  11. } elseif ($name === 'attributes') { //v1.11.0
  12. return $this->pdo->exec('ALTER TABLE `_feed` ADD COLUMN attributes TEXT') !== false;
  13. }
  14. } catch (Exception $e) {
  15. Minz_Log::error(__method__ . ' error: ' . $e->getMessage());
  16. }
  17. return false;
  18. }
  19. /** @param array<string> $errorInfo */
  20. protected function autoUpdateDb(array $errorInfo): bool {
  21. if (isset($errorInfo[0])) {
  22. if ($errorInfo[0] === FreshRSS_DatabaseDAO::ER_BAD_FIELD_ERROR || $errorInfo[0] === FreshRSS_DatabaseDAOPGSQL::UNDEFINED_COLUMN) {
  23. $errorLines = explode("\n", $errorInfo[2], 2); // The relevant column name is on the first line, other lines are noise
  24. foreach (['attributes', 'kind'] as $column) {
  25. if (stripos($errorLines[0], $column) !== false) {
  26. return $this->addColumn($column);
  27. }
  28. }
  29. }
  30. }
  31. return false;
  32. }
  33. /**
  34. * @param array{'url':string,'kind':int,'category':int,'name':string,'website':string,'description':string,'lastUpdate':int,'priority'?:int,
  35. * 'pathEntries'?:string,'httpAuth':string,'error':int|bool,'ttl'?:int,'attributes'?:string|array<string|mixed>} $valuesTmp
  36. * @return int|false
  37. * @throws JsonException
  38. */
  39. public function addFeed(array $valuesTmp) {
  40. $sql = 'INSERT INTO `_feed` (url, kind, category, name, website, description, `lastUpdate`, priority, `pathEntries`, `httpAuth`, error, ttl, attributes)
  41. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
  42. $stm = $this->pdo->prepare($sql);
  43. $valuesTmp['url'] = safe_ascii($valuesTmp['url']);
  44. $valuesTmp['website'] = safe_ascii($valuesTmp['website']);
  45. if (!isset($valuesTmp['pathEntries'])) {
  46. $valuesTmp['pathEntries'] = '';
  47. }
  48. if (!isset($valuesTmp['attributes'])) {
  49. $valuesTmp['attributes'] = [];
  50. }
  51. $values = [
  52. $valuesTmp['url'],
  53. $valuesTmp['kind'] ?? FreshRSS_Feed::KIND_RSS,
  54. $valuesTmp['category'],
  55. mb_strcut(trim($valuesTmp['name']), 0, FreshRSS_DatabaseDAO::LENGTH_INDEX_UNICODE, 'UTF-8'),
  56. $valuesTmp['website'],
  57. sanitizeHTML($valuesTmp['description'], '', 1023),
  58. $valuesTmp['lastUpdate'],
  59. isset($valuesTmp['priority']) ? (int)$valuesTmp['priority'] : FreshRSS_Feed::PRIORITY_MAIN_STREAM,
  60. mb_strcut($valuesTmp['pathEntries'], 0, 511, 'UTF-8'),
  61. base64_encode($valuesTmp['httpAuth']),
  62. isset($valuesTmp['error']) ? (int)$valuesTmp['error'] : 0,
  63. isset($valuesTmp['ttl']) ? (int)$valuesTmp['ttl'] : FreshRSS_Feed::TTL_DEFAULT,
  64. is_string($valuesTmp['attributes']) ? $valuesTmp['attributes'] : json_encode($valuesTmp['attributes'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
  65. ];
  66. if ($stm !== false && $stm->execute($values)) {
  67. $feedId = $this->pdo->lastInsertId('`_feed_id_seq`');
  68. return $feedId === false ? false : (int)$feedId;
  69. } else {
  70. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  71. if ($this->autoUpdateDb($info)) {
  72. return $this->addFeed($valuesTmp);
  73. }
  74. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  75. return false;
  76. }
  77. }
  78. /** @return int|false */
  79. public function addFeedObject(FreshRSS_Feed $feed) {
  80. // Add feed only if we don’t find it in DB
  81. $feed_search = $this->searchByUrl($feed->url());
  82. if (!$feed_search) {
  83. $values = [
  84. 'id' => $feed->id(),
  85. 'url' => $feed->url(),
  86. 'kind' => $feed->kind(),
  87. 'category' => $feed->categoryId(),
  88. 'name' => $feed->name(true),
  89. 'website' => $feed->website(),
  90. 'description' => $feed->description(),
  91. 'lastUpdate' => 0,
  92. 'error' => false,
  93. 'pathEntries' => $feed->pathEntries(),
  94. 'httpAuth' => $feed->httpAuth(),
  95. 'ttl' => $feed->ttl(true),
  96. 'attributes' => $feed->attributes(),
  97. ];
  98. $id = $this->addFeed($values);
  99. if ($id) {
  100. $feed->_id($id);
  101. $feed->faviconPrepare();
  102. }
  103. return $id;
  104. } else {
  105. // The feed already exists so make sure it is not muted
  106. $feed->_ttl($feed_search->ttl());
  107. $feed->_mute(false);
  108. // Merge existing and import attributes
  109. $existingAttributes = $feed_search->attributes();
  110. $importAttributes = $feed->attributes();
  111. $feed->_attributes('', array_replace_recursive($existingAttributes, $importAttributes));
  112. // Update some values of the existing feed using the import
  113. $values = [
  114. 'kind' => $feed->kind(),
  115. 'name' => $feed->name(true),
  116. 'website' => $feed->website(),
  117. 'description' => $feed->description(),
  118. 'pathEntries' => $feed->pathEntries(),
  119. 'ttl' => $feed->ttl(true),
  120. 'attributes' => $feed->attributes(),
  121. ];
  122. if (!$this->updateFeed($feed_search->id(), $values)) {
  123. return false;
  124. }
  125. return $feed_search->id();
  126. }
  127. }
  128. /**
  129. * @param array{'url'?:string,'kind'?:int,'category'?:int,'name'?:string,'website'?:string,'description'?:string,'lastUpdate'?:int,'priority'?:int,
  130. * 'pathEntries'?:string,'httpAuth'?:string,'error'?:int,'ttl'?:int,'attributes'?:string|array<string,mixed>} $valuesTmp $valuesTmp
  131. * @return int|false
  132. */
  133. public function updateFeed(int $id, array $valuesTmp) {
  134. $values = [];
  135. $originalValues = $valuesTmp;
  136. if (isset($valuesTmp['name'])) {
  137. $valuesTmp['name'] = mb_strcut(trim($valuesTmp['name']), 0, FreshRSS_DatabaseDAO::LENGTH_INDEX_UNICODE, 'UTF-8');
  138. }
  139. if (isset($valuesTmp['url'])) {
  140. $valuesTmp['url'] = safe_ascii($valuesTmp['url']);
  141. }
  142. if (isset($valuesTmp['website'])) {
  143. $valuesTmp['website'] = safe_ascii($valuesTmp['website']);
  144. }
  145. $set = '';
  146. foreach ($valuesTmp as $key => $v) {
  147. $set .= '`' . $key . '`=?, ';
  148. if ($key === 'httpAuth') {
  149. $valuesTmp[$key] = base64_encode($v);
  150. } elseif ($key === 'attributes') {
  151. $valuesTmp[$key] = is_string($valuesTmp[$key]) ? $valuesTmp[$key] : json_encode($valuesTmp[$key], JSON_UNESCAPED_SLASHES);
  152. }
  153. }
  154. $set = substr($set, 0, -2);
  155. $sql = 'UPDATE `_feed` SET ' . $set . ' WHERE id=?';
  156. $stm = $this->pdo->prepare($sql);
  157. foreach ($valuesTmp as $v) {
  158. $values[] = $v;
  159. }
  160. $values[] = $id;
  161. if ($stm !== false && $stm->execute($values)) {
  162. return $stm->rowCount();
  163. } else {
  164. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  165. if ($this->autoUpdateDb($info)) {
  166. return $this->updateFeed($id, $originalValues);
  167. }
  168. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info) . ' for feed ' . $id);
  169. return false;
  170. }
  171. }
  172. /**
  173. * @param string|array<mixed>|bool|int|null $value
  174. * @return int|false
  175. */
  176. public function updateFeedAttribute(FreshRSS_Feed $feed, string $key, $value) {
  177. $feed->_attributes($key, $value);
  178. return $this->updateFeed(
  179. $feed->id(),
  180. ['attributes' => $feed->attributes()]
  181. );
  182. }
  183. /**
  184. * @return int|false
  185. * @see updateCachedValue()
  186. */
  187. public function updateLastUpdate(int $id, bool $inError = false, int $mtime = 0) {
  188. $sql = 'UPDATE `_feed` SET `lastUpdate`=?, error=? WHERE id=?';
  189. $values = [
  190. $mtime <= 0 ? time() : $mtime,
  191. $inError ? 1 : 0,
  192. $id,
  193. ];
  194. $stm = $this->pdo->prepare($sql);
  195. if ($stm !== false && $stm->execute($values)) {
  196. return $stm->rowCount();
  197. } else {
  198. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  199. Minz_Log::warning(__METHOD__ . ' error: ' . $sql . ' : ' . json_encode($info));
  200. return false;
  201. }
  202. }
  203. /** @return int|false */
  204. public function mute(int $id, bool $value = true) {
  205. $sql = 'UPDATE `_feed` SET ttl=' . ($value ? '-' : '') . 'ABS(ttl) WHERE id=' . intval($id);
  206. return $this->pdo->exec($sql);
  207. }
  208. /** @return int|false */
  209. public function changeCategory(int $idOldCat, int $idNewCat) {
  210. $catDAO = FreshRSS_Factory::createCategoryDao();
  211. $newCat = $catDAO->searchById($idNewCat);
  212. if ($newCat === null) {
  213. $newCat = $catDAO->getDefault();
  214. }
  215. $sql = 'UPDATE `_feed` SET category=? WHERE category=?';
  216. $stm = $this->pdo->prepare($sql);
  217. $values = [
  218. $newCat->id(),
  219. $idOldCat,
  220. ];
  221. if ($stm !== false && $stm->execute($values)) {
  222. return $stm->rowCount();
  223. } else {
  224. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  225. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  226. return false;
  227. }
  228. }
  229. /** @return int|false */
  230. public function deleteFeed(int $id) {
  231. $sql = 'DELETE FROM `_feed` WHERE id=?';
  232. $stm = $this->pdo->prepare($sql);
  233. $values = [$id];
  234. if ($stm !== false && $stm->execute($values)) {
  235. return $stm->rowCount();
  236. } else {
  237. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  238. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  239. return false;
  240. }
  241. }
  242. /**
  243. * @param bool|null $muted to include only muted feeds
  244. * @return int|false
  245. */
  246. public function deleteFeedByCategory(int $id, ?bool $muted = null) {
  247. $sql = 'DELETE FROM `_feed` WHERE category=?';
  248. if ($muted) {
  249. $sql .= ' AND ttl < 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 == null ? $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. return;
  272. }
  273. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  274. yield $row;
  275. }
  276. }
  277. public function searchById(int $id): ?FreshRSS_Feed {
  278. $sql = 'SELECT * FROM `_feed` WHERE id=:id';
  279. $res = $this->fetchAssoc($sql, [':id' => $id]);
  280. if ($res == null) {
  281. return null;
  282. }
  283. /** @var array<int,array{'url':string,'kind':int,'category':int,'name':string,'website':string,'lastUpdate':int,
  284. * 'priority'?:int,'pathEntries'?:string,'httpAuth':string,'error':int,'ttl'?:int,'attributes'?:string}> $res */
  285. $feeds = self::daoToFeed($res);
  286. return $feeds[$id] ?? null;
  287. }
  288. public function searchByUrl(string $url): ?FreshRSS_Feed {
  289. $sql = 'SELECT * FROM `_feed` WHERE url=:url';
  290. $res = $this->fetchAssoc($sql, [':url' => $url]);
  291. /** @var array<int,array{'url':string,'kind':int,'category':int,'name':string,'website':string,'lastUpdate':int,
  292. * 'priority'?:int,'pathEntries'?:string,'httpAuth':string,'error':int,'ttl'?:int,'attributes'?:string}> $res */
  293. return empty($res[0]) ? null : (current(self::daoToFeed($res)) ?: null);
  294. }
  295. /** @return array<int> */
  296. public function listFeedsIds(): array {
  297. $sql = 'SELECT id FROM `_feed`';
  298. /** @var array<int> $res */
  299. $res = $this->fetchColumn($sql, 0) ?? [];
  300. return $res;
  301. }
  302. /**
  303. * @return array<FreshRSS_Feed>
  304. */
  305. public function listFeeds(): array {
  306. $sql = 'SELECT * FROM `_feed` ORDER BY name';
  307. $res = $this->fetchAssoc($sql);
  308. /** @var array<array{'url':string,'kind':int,'category':int,'name':string,'website':string,'lastUpdate':int,
  309. * 'priority':int,'pathEntries':string,'httpAuth':string,'error':int,'ttl':int,'attributes':string}>|null $res */
  310. return $res == null ? [] : self::daoToFeed($res);
  311. }
  312. /** @return array<string,string> */
  313. public function listFeedsNewestItemUsec(?int $id_feed = null): array {
  314. $sql = 'SELECT id_feed, MAX(id) as newest_item_us FROM `_entry` ';
  315. if ($id_feed === null) {
  316. $sql .= 'GROUP BY id_feed';
  317. } else {
  318. $sql .= 'WHERE id_feed=' . intval($id_feed);
  319. }
  320. $res = $this->fetchAssoc($sql);
  321. /** @var array<array{'id_feed':int,'newest_item_us':string}>|null $res */
  322. if ($res == null) {
  323. return [];
  324. }
  325. $newestItemUsec = [];
  326. foreach ($res as $line) {
  327. $newestItemUsec['f_' . $line['id_feed']] = $line['newest_item_us'];
  328. }
  329. return $newestItemUsec;
  330. }
  331. /**
  332. * @param int $defaultCacheDuration Use -1 to return all feeds, without filtering them by TTL.
  333. * @return array<FreshRSS_Feed>
  334. */
  335. public function listFeedsOrderUpdate(int $defaultCacheDuration = 3600, int $limit = 0): array {
  336. $this->updateTTL();
  337. $sql = 'SELECT id, url, kind, name, website, `lastUpdate`, `pathEntries`, `httpAuth`, ttl, attributes '
  338. . 'FROM `_feed` '
  339. . ($defaultCacheDuration < 0 ? '' : 'WHERE ttl >= ' . FreshRSS_Feed::TTL_DEFAULT
  340. . ' AND `lastUpdate` < (' . (time() + 60)
  341. . '-(CASE WHEN ttl=' . FreshRSS_Feed::TTL_DEFAULT . ' THEN ' . intval($defaultCacheDuration) . ' ELSE ttl END)) ')
  342. . 'ORDER BY `lastUpdate` '
  343. . ($limit < 1 ? '' : 'LIMIT ' . intval($limit));
  344. $stm = $this->pdo->query($sql);
  345. if ($stm !== false) {
  346. return self::daoToFeed($stm->fetchAll(PDO::FETCH_ASSOC));
  347. } else {
  348. $info = $this->pdo->errorInfo();
  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 array<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 array<string> $res */
  362. return $res;
  363. }
  364. /**
  365. * @param bool|null $muted to include only muted feeds
  366. * @return array<FreshRSS_Feed>
  367. */
  368. public function listByCategory(int $cat, ?bool $muted = null): array {
  369. $sql = 'SELECT * FROM `_feed` WHERE category=:category';
  370. if ($muted) {
  371. $sql .= ' AND ttl < 0';
  372. }
  373. $res = $this->fetchAssoc($sql, [':category' => $cat]);
  374. if ($res == null) {
  375. return [];
  376. }
  377. /**
  378. * @var array<int,array{'url':string,'kind':int,'category':int,'name':string,'website':string,'lastUpdate':int,
  379. * 'priority'?:int,'pathEntries'?:string,'httpAuth':string,'error':int,'ttl'?:int,'attributes'?:string}> $res
  380. */
  381. $feeds = self::daoToFeed($res);
  382. usort($feeds, static function (FreshRSS_Feed $a, FreshRSS_Feed $b) {
  383. return strnatcasecmp($a->name(), $b->name());
  384. });
  385. return $feeds;
  386. }
  387. public function countEntries(int $id): int {
  388. $sql = 'SELECT COUNT(*) AS count FROM `_entry` WHERE id_feed=:id_feed';
  389. $res = $this->fetchColumn($sql, 0, ['id_feed' => $id]);
  390. return isset($res[0]) ? (int)($res[0]) : -1;
  391. }
  392. public function countNotRead(int $id): int {
  393. $sql = 'SELECT COUNT(*) AS count FROM `_entry` WHERE id_feed=:id_feed AND is_read=0';
  394. $res = $this->fetchColumn($sql, 0, ['id_feed' => $id]);
  395. return isset($res[0]) ? (int)($res[0]) : -1;
  396. }
  397. /**
  398. * @return int|false
  399. */
  400. public function updateCachedValues(int $id = 0) {
  401. //2 sub-requests with FOREIGN KEY(e.id_feed), INDEX(e.is_read) faster than 1 request with GROUP BY or CASE
  402. $sql = 'UPDATE `_feed` '
  403. . 'SET `cache_nbEntries`=(SELECT COUNT(e1.id) FROM `_entry` e1 WHERE e1.id_feed=`_feed`.id),'
  404. . '`cache_nbUnreads`=(SELECT COUNT(e2.id) FROM `_entry` e2 WHERE e2.id_feed=`_feed`.id AND e2.is_read=0)'
  405. . ($id != 0 ? ' WHERE id=:id' : '');
  406. $stm = $this->pdo->prepare($sql);
  407. if ($stm !== false && $id != 0) {
  408. $stm->bindParam(':id', $id, PDO::PARAM_INT);
  409. }
  410. if ($stm !== false && $stm->execute()) {
  411. return $stm->rowCount();
  412. } else {
  413. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  414. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  415. return false;
  416. }
  417. }
  418. /**
  419. * Remember to call updateCachedValues() after calling this function
  420. * @return int|false number of lines affected or false in case of error
  421. */
  422. public function keepMaxUnread(int $id, int $n) {
  423. //Double SELECT for MySQL workaround ERROR 1093 (HY000)
  424. $sql = <<<'SQL'
  425. UPDATE `_entry` SET is_read=1
  426. WHERE id_feed=:id_feed1 AND is_read=0 AND id <= (SELECT e3.id FROM (
  427. SELECT e2.id FROM `_entry` e2
  428. WHERE e2.id_feed=:id_feed2 AND e2.is_read=0
  429. ORDER BY e2.id DESC
  430. LIMIT 1
  431. OFFSET :limit) e3)
  432. SQL;
  433. if (($stm = $this->pdo->prepare($sql)) &&
  434. $stm->bindParam(':id_feed1', $id, PDO::PARAM_INT) &&
  435. $stm->bindParam(':id_feed2', $id, PDO::PARAM_INT) &&
  436. $stm->bindParam(':limit', $n, PDO::PARAM_INT) &&
  437. $stm->execute()) {
  438. return $stm->rowCount();
  439. } else {
  440. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  441. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  442. return false;
  443. }
  444. }
  445. /**
  446. * Remember to call updateCachedValues() after calling this function
  447. * @return int|false number of lines affected or false in case of error
  448. */
  449. public function markAsReadUponGone(int $id) {
  450. //Double SELECT for MySQL workaround ERROR 1093 (HY000)
  451. $sql = <<<'SQL'
  452. UPDATE `_entry` SET is_read=1
  453. WHERE id_feed=:id_feed1 AND is_read=0 AND (
  454. `lastSeen` + 60 < (SELECT s1.maxlastseen FROM (
  455. SELECT MAX(e2.`lastSeen`) AS maxlastseen FROM `_entry` e2 WHERE e2.id_feed = :id_feed2
  456. ) s1)
  457. )
  458. SQL;
  459. if (($stm = $this->pdo->prepare($sql)) &&
  460. $stm->bindParam(':id_feed1', $id, PDO::PARAM_INT) &&
  461. $stm->bindParam(':id_feed2', $id, PDO::PARAM_INT) &&
  462. $stm->execute()) {
  463. return $stm->rowCount();
  464. } else {
  465. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  466. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  467. return false;
  468. }
  469. }
  470. /**
  471. * @return int|false
  472. */
  473. public function truncate(int $id) {
  474. $sql = 'DELETE FROM `_entry` WHERE id_feed=:id';
  475. $stm = $this->pdo->prepare($sql);
  476. $this->pdo->beginTransaction();
  477. if (!($stm !== false &&
  478. $stm->bindParam(':id', $id, PDO::PARAM_INT) &&
  479. $stm->execute())) {
  480. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  481. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  482. $this->pdo->rollBack();
  483. return false;
  484. }
  485. $affected = $stm->rowCount();
  486. $sql = 'UPDATE `_feed` SET `cache_nbEntries`=0, `cache_nbUnreads`=0, `lastUpdate`=0 WHERE id=:id';
  487. $stm = $this->pdo->prepare($sql);
  488. if (!($stm !== false &&
  489. $stm->bindParam(':id', $id, PDO::PARAM_INT) &&
  490. $stm->execute())) {
  491. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  492. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  493. $this->pdo->rollBack();
  494. return false;
  495. }
  496. $this->pdo->commit();
  497. return $affected;
  498. }
  499. public function purge(): bool {
  500. $sql = 'DELETE FROM `_entry`';
  501. $stm = $this->pdo->prepare($sql);
  502. $this->pdo->beginTransaction();
  503. if (!($stm && $stm->execute())) {
  504. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  505. Minz_Log::error('SQL error ' . __METHOD__ . ' A ' . json_encode($info));
  506. $this->pdo->rollBack();
  507. return false;
  508. }
  509. $sql = 'UPDATE `_feed` SET `cache_nbEntries` = 0, `cache_nbUnreads` = 0';
  510. $stm = $this->pdo->prepare($sql);
  511. if (!($stm && $stm->execute())) {
  512. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  513. Minz_Log::error('SQL error ' . __METHOD__ . ' B ' . json_encode($info));
  514. $this->pdo->rollBack();
  515. return false;
  516. }
  517. return $this->pdo->commit();
  518. }
  519. /**
  520. * @param array<int,array{'id'?:int,'url'?:string,'kind'?:int,'category'?:int,'name'?:string,'website'?:string,'description'?:string,'lastUpdate'?:int,'priority'?:int,
  521. * 'pathEntries'?:string,'httpAuth'?:string,'error'?:int|bool,'ttl'?:int,'attributes'?:string,'cache_nbUnreads'?:int,'cache_nbEntries'?:int}> $listDAO
  522. * @return array<int,FreshRSS_Feed>
  523. */
  524. public static function daoToFeed(array $listDAO, ?int $catID = null): array {
  525. $list = [];
  526. foreach ($listDAO as $key => $dao) {
  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'] ?? 0);
  552. $myFeed->_nbEntries($dao['cache_nbEntries'] ?? 0);
  553. if (isset($dao['id'])) {
  554. $myFeed->_id($dao['id']);
  555. }
  556. $list[$key] = $myFeed;
  557. }
  558. return $list;
  559. }
  560. public function updateTTL(): void {
  561. $sql = 'UPDATE `_feed` SET ttl=:new_value WHERE ttl=:old_value';
  562. $stm = $this->pdo->prepare($sql);
  563. if (!($stm && $stm->execute([':new_value' => FreshRSS_Feed::TTL_DEFAULT, ':old_value' => -2]))) {
  564. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  565. Minz_Log::error('SQL error ' . __METHOD__ . ' A ' . json_encode($info));
  566. $sql2 = 'ALTER TABLE `_feed` ADD COLUMN ttl INT NOT NULL DEFAULT ' . FreshRSS_Feed::TTL_DEFAULT; //v0.7.3
  567. $stm = $this->pdo->query($sql2);
  568. if ($stm === false) {
  569. $info = $this->pdo->errorInfo();
  570. Minz_Log::error('SQL error ' . __METHOD__ . ' B ' . json_encode($info));
  571. }
  572. } else {
  573. $stm->execute([':new_value' => -3600, ':old_value' => -1]);
  574. }
  575. }
  576. public function count(): int {
  577. $sql = 'SELECT COUNT(e.id) AS count FROM `_feed` e';
  578. $stm = $this->pdo->query($sql);
  579. if ($stm == false) {
  580. return -1;
  581. }
  582. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  583. return $res[0] ?? 0;
  584. }
  585. }