FeedDAO.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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. }
  12. } catch (Exception $e) {
  13. Minz_Log::error(__method__ . ' error: ' . $e->getMessage());
  14. }
  15. return false;
  16. }
  17. /** @param array<string> $errorInfo */
  18. protected function autoUpdateDb(array $errorInfo): bool {
  19. if (isset($errorInfo[0])) {
  20. if ($errorInfo[0] === FreshRSS_DatabaseDAO::ER_BAD_FIELD_ERROR || $errorInfo[0] === FreshRSS_DatabaseDAOPGSQL::UNDEFINED_COLUMN) {
  21. $errorLines = explode("\n", $errorInfo[2], 2); // The relevant column name is on the first line, other lines are noise
  22. foreach (['kind'] as $column) {
  23. if (stripos($errorLines[0], $column) !== false) {
  24. return $this->addColumn($column);
  25. }
  26. }
  27. }
  28. }
  29. return false;
  30. }
  31. /**
  32. * @param array{'url':string,'kind':int,'category':int,'name':string,'website':string,'description':string,'lastUpdate':int,'priority'?:int,
  33. * 'pathEntries'?:string,'httpAuth':string,'error':int|bool,'ttl'?:int,'attributes'?:string|array<string|mixed>} $valuesTmp
  34. * @return int|false
  35. * @throws JsonException
  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'], '', 1023),
  56. $valuesTmp['lastUpdate'],
  57. isset($valuesTmp['priority']) ? (int)$valuesTmp['priority'] : FreshRSS_Feed::PRIORITY_MAIN_STREAM,
  58. mb_strcut($valuesTmp['pathEntries'], 0, 511, '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 string|array<mixed>|bool|int|null $value
  172. * @return int|false
  173. */
  174. public function updateFeedAttribute(FreshRSS_Feed $feed, string $key, $value) {
  175. $feed->_attributes($key, $value);
  176. return $this->updateFeed(
  177. $feed->id(),
  178. ['attributes' => $feed->attributes()]
  179. );
  180. }
  181. /**
  182. * @return int|false
  183. * @see updateCachedValue()
  184. */
  185. public function updateLastUpdate(int $id, bool $inError = false, int $mtime = 0) {
  186. $sql = 'UPDATE `_feed` SET `lastUpdate`=?, error=? WHERE id=?';
  187. $values = [
  188. $mtime <= 0 ? time() : $mtime,
  189. $inError ? 1 : 0,
  190. $id,
  191. ];
  192. $stm = $this->pdo->prepare($sql);
  193. if ($stm !== false && $stm->execute($values)) {
  194. return $stm->rowCount();
  195. } else {
  196. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  197. Minz_Log::warning(__METHOD__ . ' error: ' . $sql . ' : ' . json_encode($info));
  198. return false;
  199. }
  200. }
  201. /** @return int|false */
  202. public function mute(int $id, bool $value = true) {
  203. $sql = 'UPDATE `_feed` SET ttl=' . ($value ? '-' : '') . 'ABS(ttl) WHERE id=' . intval($id);
  204. return $this->pdo->exec($sql);
  205. }
  206. /** @return int|false */
  207. public function changeCategory(int $idOldCat, int $idNewCat) {
  208. $catDAO = FreshRSS_Factory::createCategoryDao();
  209. $newCat = $catDAO->searchById($idNewCat);
  210. if ($newCat === null) {
  211. $newCat = $catDAO->getDefault();
  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 == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  223. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  224. return false;
  225. }
  226. }
  227. /** @return int|false */
  228. public function deleteFeed(int $id) {
  229. $sql = 'DELETE FROM `_feed` WHERE id=?';
  230. $stm = $this->pdo->prepare($sql);
  231. $values = [$id];
  232. if ($stm !== false && $stm->execute($values)) {
  233. return $stm->rowCount();
  234. } else {
  235. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  236. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  237. return false;
  238. }
  239. }
  240. /**
  241. * @param bool|null $muted to include only muted feeds
  242. * @return int|false
  243. */
  244. public function deleteFeedByCategory(int $id, ?bool $muted = null) {
  245. $sql = 'DELETE FROM `_feed` WHERE category=?';
  246. if ($muted) {
  247. $sql .= ' AND ttl < 0';
  248. }
  249. $stm = $this->pdo->prepare($sql);
  250. $values = [$id];
  251. if ($stm !== false && $stm->execute($values)) {
  252. return $stm->rowCount();
  253. } else {
  254. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  255. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  256. return false;
  257. }
  258. }
  259. /** @return Traversable<array{'id':int,'url':string,'kind':int,'category':int,'name':string,'website':string,'description':string,'lastUpdate':int,'priority'?:int,
  260. * 'pathEntries'?:string,'httpAuth':string,'error':int|bool,'ttl'?:int,'attributes'?:string}> */
  261. public function selectAll(): Traversable {
  262. $sql = <<<'SQL'
  263. SELECT id, url, kind, category, name, website, description, `lastUpdate`,
  264. priority, `pathEntries`, `httpAuth`, error, ttl, attributes
  265. FROM `_feed`
  266. SQL;
  267. $stm = $this->pdo->query($sql);
  268. if ($stm === false) {
  269. return;
  270. }
  271. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  272. yield $row;
  273. }
  274. }
  275. public function searchById(int $id): ?FreshRSS_Feed {
  276. $sql = 'SELECT * FROM `_feed` WHERE id=:id';
  277. $res = $this->fetchAssoc($sql, [':id' => $id]);
  278. if ($res == null) {
  279. return null;
  280. }
  281. /** @var array<int,array{'url':string,'kind':int,'category':int,'name':string,'website':string,'lastUpdate':int,
  282. * 'priority'?:int,'pathEntries'?:string,'httpAuth':string,'error':int,'ttl'?:int,'attributes'?:string}> $res */
  283. $feeds = self::daoToFeed($res);
  284. return $feeds[$id] ?? null;
  285. }
  286. public function searchByUrl(string $url): ?FreshRSS_Feed {
  287. $sql = 'SELECT * FROM `_feed` WHERE url=:url';
  288. $res = $this->fetchAssoc($sql, [':url' => $url]);
  289. /** @var array<int,array{'url':string,'kind':int,'category':int,'name':string,'website':string,'lastUpdate':int,
  290. * 'priority'?:int,'pathEntries'?:string,'httpAuth':string,'error':int,'ttl'?:int,'attributes'?:string}> $res */
  291. return empty($res[0]) ? null : (current(self::daoToFeed($res)) ?: null);
  292. }
  293. /** @return array<int> */
  294. public function listFeedsIds(): array {
  295. $sql = 'SELECT id FROM `_feed`';
  296. /** @var array<int> $res */
  297. $res = $this->fetchColumn($sql, 0) ?? [];
  298. return $res;
  299. }
  300. /**
  301. * @return array<FreshRSS_Feed>
  302. */
  303. public function listFeeds(): array {
  304. $sql = 'SELECT * FROM `_feed` ORDER BY name';
  305. $res = $this->fetchAssoc($sql);
  306. /** @var array<array{'url':string,'kind':int,'category':int,'name':string,'website':string,'lastUpdate':int,
  307. * 'priority':int,'pathEntries':string,'httpAuth':string,'error':int,'ttl':int,'attributes':string}>|null $res */
  308. return $res == null ? [] : self::daoToFeed($res);
  309. }
  310. /** @return array<string,string> */
  311. public function listFeedsNewestItemUsec(?int $id_feed = null): array {
  312. $sql = 'SELECT id_feed, MAX(id) as newest_item_us FROM `_entry` ';
  313. if ($id_feed === null) {
  314. $sql .= 'GROUP BY id_feed';
  315. } else {
  316. $sql .= 'WHERE id_feed=' . intval($id_feed);
  317. }
  318. $res = $this->fetchAssoc($sql);
  319. /** @var array<array{'id_feed':int,'newest_item_us':string}>|null $res */
  320. if ($res == null) {
  321. return [];
  322. }
  323. $newestItemUsec = [];
  324. foreach ($res as $line) {
  325. $newestItemUsec['f_' . $line['id_feed']] = $line['newest_item_us'];
  326. }
  327. return $newestItemUsec;
  328. }
  329. /**
  330. * @param int $defaultCacheDuration Use -1 to return all feeds, without filtering them by TTL.
  331. * @return array<FreshRSS_Feed>
  332. */
  333. public function listFeedsOrderUpdate(int $defaultCacheDuration = 3600, int $limit = 0): array {
  334. $sql = 'SELECT id, url, kind, name, website, `lastUpdate`, `pathEntries`, `httpAuth`, ttl, attributes '
  335. . 'FROM `_feed` '
  336. . ($defaultCacheDuration < 0 ? '' : 'WHERE ttl >= ' . FreshRSS_Feed::TTL_DEFAULT
  337. . ' AND `lastUpdate` < (' . (time() + 60)
  338. . '-(CASE WHEN ttl=' . FreshRSS_Feed::TTL_DEFAULT . ' THEN ' . intval($defaultCacheDuration) . ' ELSE ttl END)) ')
  339. . 'ORDER BY `lastUpdate` '
  340. . ($limit < 1 ? '' : 'LIMIT ' . intval($limit));
  341. $stm = $this->pdo->query($sql);
  342. if ($stm !== false) {
  343. return self::daoToFeed($stm->fetchAll(PDO::FETCH_ASSOC));
  344. } else {
  345. $info = $this->pdo->errorInfo();
  346. if ($this->autoUpdateDb($info)) {
  347. return $this->listFeedsOrderUpdate($defaultCacheDuration, $limit);
  348. }
  349. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  350. return [];
  351. }
  352. }
  353. /** @return array<string> */
  354. public function listTitles(int $id, int $limit = 0): array {
  355. $sql = 'SELECT title FROM `_entry` WHERE id_feed=:id_feed ORDER BY id DESC'
  356. . ($limit < 1 ? '' : ' LIMIT ' . intval($limit));
  357. $res = $this->fetchColumn($sql, 0, [':id_feed' => $id]) ?? [];
  358. /** @var array<string> $res */
  359. return $res;
  360. }
  361. /**
  362. * @param bool|null $muted to include only muted feeds
  363. * @return array<FreshRSS_Feed>
  364. */
  365. public function listByCategory(int $cat, ?bool $muted = null): array {
  366. $sql = 'SELECT * FROM `_feed` WHERE category=:category';
  367. if ($muted) {
  368. $sql .= ' AND ttl < 0';
  369. }
  370. $res = $this->fetchAssoc($sql, [':category' => $cat]);
  371. if ($res == null) {
  372. return [];
  373. }
  374. /**
  375. * @var array<int,array{'url':string,'kind':int,'category':int,'name':string,'website':string,'lastUpdate':int,
  376. * 'priority'?:int,'pathEntries'?:string,'httpAuth':string,'error':int,'ttl'?:int,'attributes'?:string}> $res
  377. */
  378. $feeds = self::daoToFeed($res);
  379. usort($feeds, static function (FreshRSS_Feed $a, FreshRSS_Feed $b) {
  380. return strnatcasecmp($a->name(), $b->name());
  381. });
  382. return $feeds;
  383. }
  384. public function countEntries(int $id): int {
  385. $sql = 'SELECT COUNT(*) AS count FROM `_entry` WHERE id_feed=:id_feed';
  386. $res = $this->fetchColumn($sql, 0, ['id_feed' => $id]);
  387. return isset($res[0]) ? (int)($res[0]) : -1;
  388. }
  389. public function countNotRead(int $id): int {
  390. $sql = 'SELECT COUNT(*) AS count FROM `_entry` WHERE id_feed=:id_feed AND is_read=0';
  391. $res = $this->fetchColumn($sql, 0, ['id_feed' => $id]);
  392. return isset($res[0]) ? (int)($res[0]) : -1;
  393. }
  394. /**
  395. * @return int|false
  396. */
  397. public function updateCachedValues(int $id = 0) {
  398. //2 sub-requests with FOREIGN KEY(e.id_feed), INDEX(e.is_read) faster than 1 request with GROUP BY or CASE
  399. $sql = 'UPDATE `_feed` '
  400. . 'SET `cache_nbEntries`=(SELECT COUNT(e1.id) FROM `_entry` e1 WHERE e1.id_feed=`_feed`.id),'
  401. . '`cache_nbUnreads`=(SELECT COUNT(e2.id) FROM `_entry` e2 WHERE e2.id_feed=`_feed`.id AND e2.is_read=0)'
  402. . ($id != 0 ? ' WHERE id=:id' : '');
  403. $stm = $this->pdo->prepare($sql);
  404. if ($stm !== false && $id != 0) {
  405. $stm->bindParam(':id', $id, PDO::PARAM_INT);
  406. }
  407. if ($stm !== false && $stm->execute()) {
  408. return $stm->rowCount();
  409. } else {
  410. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  411. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  412. return false;
  413. }
  414. }
  415. /**
  416. * Remember to call updateCachedValues() after calling this function
  417. * @return int|false number of lines affected or false in case of error
  418. */
  419. public function keepMaxUnread(int $id, int $n) {
  420. //Double SELECT for MySQL workaround ERROR 1093 (HY000)
  421. $sql = <<<'SQL'
  422. UPDATE `_entry` SET is_read=1
  423. WHERE id_feed=:id_feed1 AND is_read=0 AND id <= (SELECT e3.id FROM (
  424. SELECT e2.id FROM `_entry` e2
  425. WHERE e2.id_feed=:id_feed2 AND e2.is_read=0
  426. ORDER BY e2.id DESC
  427. LIMIT 1
  428. OFFSET :limit) e3)
  429. SQL;
  430. if (($stm = $this->pdo->prepare($sql)) &&
  431. $stm->bindParam(':id_feed1', $id, PDO::PARAM_INT) &&
  432. $stm->bindParam(':id_feed2', $id, PDO::PARAM_INT) &&
  433. $stm->bindParam(':limit', $n, PDO::PARAM_INT) &&
  434. $stm->execute()) {
  435. return $stm->rowCount();
  436. } else {
  437. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  438. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  439. return false;
  440. }
  441. }
  442. /**
  443. * Remember to call updateCachedValues() after calling this function
  444. * @return int|false number of lines affected or false in case of error
  445. */
  446. public function markAsReadUponGone(int $id) {
  447. //Double SELECT for MySQL workaround ERROR 1093 (HY000)
  448. $sql = <<<'SQL'
  449. UPDATE `_entry` SET is_read=1
  450. WHERE id_feed=:id_feed1 AND is_read=0 AND (
  451. `lastSeen` + 60 < (SELECT s1.maxlastseen FROM (
  452. SELECT MAX(e2.`lastSeen`) AS maxlastseen FROM `_entry` e2 WHERE e2.id_feed = :id_feed2
  453. ) s1)
  454. )
  455. SQL;
  456. if (($stm = $this->pdo->prepare($sql)) &&
  457. $stm->bindParam(':id_feed1', $id, PDO::PARAM_INT) &&
  458. $stm->bindParam(':id_feed2', $id, PDO::PARAM_INT) &&
  459. $stm->execute()) {
  460. return $stm->rowCount();
  461. } else {
  462. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  463. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  464. return false;
  465. }
  466. }
  467. /**
  468. * @return int|false
  469. */
  470. public function truncate(int $id) {
  471. $sql = 'DELETE FROM `_entry` WHERE id_feed=:id';
  472. $stm = $this->pdo->prepare($sql);
  473. $this->pdo->beginTransaction();
  474. if (!($stm !== false &&
  475. $stm->bindParam(':id', $id, PDO::PARAM_INT) &&
  476. $stm->execute())) {
  477. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  478. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  479. $this->pdo->rollBack();
  480. return false;
  481. }
  482. $affected = $stm->rowCount();
  483. $sql = 'UPDATE `_feed` SET `cache_nbEntries`=0, `cache_nbUnreads`=0, `lastUpdate`=0 WHERE id=:id';
  484. $stm = $this->pdo->prepare($sql);
  485. if (!($stm !== false &&
  486. $stm->bindParam(':id', $id, PDO::PARAM_INT) &&
  487. $stm->execute())) {
  488. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  489. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  490. $this->pdo->rollBack();
  491. return false;
  492. }
  493. $this->pdo->commit();
  494. return $affected;
  495. }
  496. public function purge(): bool {
  497. $sql = 'DELETE FROM `_entry`';
  498. $stm = $this->pdo->prepare($sql);
  499. $this->pdo->beginTransaction();
  500. if (!($stm && $stm->execute())) {
  501. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  502. Minz_Log::error('SQL error ' . __METHOD__ . ' A ' . json_encode($info));
  503. $this->pdo->rollBack();
  504. return false;
  505. }
  506. $sql = 'UPDATE `_feed` SET `cache_nbEntries` = 0, `cache_nbUnreads` = 0';
  507. $stm = $this->pdo->prepare($sql);
  508. if (!($stm && $stm->execute())) {
  509. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  510. Minz_Log::error('SQL error ' . __METHOD__ . ' B ' . json_encode($info));
  511. $this->pdo->rollBack();
  512. return false;
  513. }
  514. return $this->pdo->commit();
  515. }
  516. /**
  517. * @param array<int,array{'id'?:int,'url'?:string,'kind'?:int,'category'?:int,'name'?:string,'website'?:string,'description'?:string,'lastUpdate'?:int,'priority'?:int,
  518. * 'pathEntries'?:string,'httpAuth'?:string,'error'?:int|bool,'ttl'?:int,'attributes'?:string,'cache_nbUnreads'?:int,'cache_nbEntries'?:int}> $listDAO
  519. * @return array<int,FreshRSS_Feed>
  520. */
  521. public static function daoToFeed(array $listDAO, ?int $catID = null): array {
  522. $list = [];
  523. foreach ($listDAO as $key => $dao) {
  524. if (!isset($dao['name'])) {
  525. continue;
  526. }
  527. if (isset($dao['id'])) {
  528. $key = (int)$dao['id'];
  529. }
  530. if ($catID === null) {
  531. $category = $dao['category'] ?? 0;
  532. } else {
  533. $category = $catID;
  534. }
  535. $myFeed = new FreshRSS_Feed($dao['url'] ?? '', false);
  536. $myFeed->_kind($dao['kind'] ?? FreshRSS_Feed::KIND_RSS);
  537. $myFeed->_categoryId($category);
  538. $myFeed->_name($dao['name']);
  539. $myFeed->_website($dao['website'] ?? '', false);
  540. $myFeed->_description($dao['description'] ?? '');
  541. $myFeed->_lastUpdate($dao['lastUpdate'] ?? 0);
  542. $myFeed->_priority($dao['priority'] ?? 10);
  543. $myFeed->_pathEntries($dao['pathEntries'] ?? '');
  544. $myFeed->_httpAuth(base64_decode($dao['httpAuth'] ?? '', true) ?: '');
  545. $myFeed->_error($dao['error'] ?? 0);
  546. $myFeed->_ttl($dao['ttl'] ?? FreshRSS_Feed::TTL_DEFAULT);
  547. $myFeed->_attributes('', $dao['attributes'] ?? '');
  548. $myFeed->_nbNotRead($dao['cache_nbUnreads'] ?? 0);
  549. $myFeed->_nbEntries($dao['cache_nbEntries'] ?? 0);
  550. if (isset($dao['id'])) {
  551. $myFeed->_id($dao['id']);
  552. }
  553. $list[$key] = $myFeed;
  554. }
  555. return $list;
  556. }
  557. public function count(): int {
  558. $sql = 'SELECT COUNT(e.id) AS count FROM `_feed` e';
  559. $stm = $this->pdo->query($sql);
  560. if ($stm == false) {
  561. return -1;
  562. }
  563. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  564. return $res[0] ?? 0;
  565. }
  566. }