EntryDAO.php 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429
  1. <?php
  2. declare(strict_types=1);
  3. class FreshRSS_EntryDAO extends Minz_ModelPdo {
  4. public static function isCompressed(): bool {
  5. return true;
  6. }
  7. public static function hasNativeHex(): bool {
  8. return true;
  9. }
  10. protected static function sqlConcat(string $s1, string $s2): string {
  11. return 'CONCAT(' . $s1 . ',' . $s2 . ')'; //MySQL
  12. }
  13. public static function sqlHexDecode(string $x): string {
  14. return 'unhex(' . $x . ')';
  15. }
  16. public static function sqlHexEncode(string $x): string {
  17. return 'hex(' . $x . ')';
  18. }
  19. public static function sqlIgnoreConflict(string $sql): string {
  20. return str_replace('INSERT INTO ', 'INSERT IGNORE INTO ', $sql);
  21. }
  22. private function updateToMediumBlob(): bool {
  23. if ($this->pdo->dbType() !== 'mysql') {
  24. return false;
  25. }
  26. Minz_Log::warning('Update MySQL table to use MEDIUMBLOB...');
  27. $sql = <<<'SQL'
  28. ALTER TABLE `_entry` MODIFY `content_bin` MEDIUMBLOB;
  29. ALTER TABLE `_entrytmp` MODIFY `content_bin` MEDIUMBLOB;
  30. SQL;
  31. try {
  32. $ok = $this->pdo->exec($sql) !== false;
  33. } catch (Exception $e) {
  34. $ok = false;
  35. Minz_Log::error(__method__ . ' error: ' . $e->getMessage());
  36. }
  37. return $ok;
  38. }
  39. protected function addColumn(string $name): bool {
  40. if ($this->pdo->inTransaction()) {
  41. $this->pdo->commit();
  42. }
  43. Minz_Log::warning(__method__ . ': ' . $name);
  44. try {
  45. if ($name === 'attributes') { //v1.20.0
  46. $sql = <<<'SQL'
  47. ALTER TABLE `_entry` ADD COLUMN attributes TEXT;
  48. ALTER TABLE `_entrytmp` ADD COLUMN attributes TEXT;
  49. SQL;
  50. return $this->pdo->exec($sql) !== false;
  51. }
  52. } catch (Exception $e) {
  53. Minz_Log::error(__method__ . ' error: ' . $e->getMessage());
  54. }
  55. return false;
  56. }
  57. //TODO: Move the database auto-updates to DatabaseDAO
  58. /** @param array<string|int> $errorInfo */
  59. protected function autoUpdateDb(array $errorInfo): bool {
  60. if (isset($errorInfo[0])) {
  61. if ($errorInfo[0] === FreshRSS_DatabaseDAO::ER_BAD_FIELD_ERROR || $errorInfo[0] === FreshRSS_DatabaseDAOPGSQL::UNDEFINED_COLUMN) {
  62. $errorLines = explode("\n", (string)$errorInfo[2], 2); // The relevant column name is on the first line, other lines are noise
  63. foreach (['attributes'] as $column) {
  64. if (stripos($errorLines[0], $column) !== false) {
  65. return $this->addColumn($column);
  66. }
  67. }
  68. }
  69. }
  70. if (isset($errorInfo[1])) {
  71. // May be a string or an int
  72. if ($errorInfo[1] == FreshRSS_DatabaseDAO::ER_DATA_TOO_LONG) {
  73. if (stripos((string)$errorInfo[2], 'content_bin') !== false) {
  74. return $this->updateToMediumBlob(); //v1.15.0
  75. }
  76. }
  77. }
  78. return false;
  79. }
  80. /**
  81. * @var PDOStatement|null|false
  82. */
  83. private $addEntryPrepared = false;
  84. /** @param array{'id':string,'guid':string,'title':string,'author':string,'content':string,'link':string,'date':int,'lastSeen':int,'hash':string,
  85. * 'is_read':bool|int|null,'is_favorite':bool|int|null,'id_feed':int,'tags':string,'attributes'?:null|string|array<string,mixed>} $valuesTmp */
  86. public function addEntry(array $valuesTmp, bool $useTmpTable = true): bool {
  87. if ($this->addEntryPrepared == null) {
  88. $sql = static::sqlIgnoreConflict(
  89. 'INSERT INTO `_' . ($useTmpTable ? 'entrytmp' : 'entry') . '` (id, guid, title, author, '
  90. . (static::isCompressed() ? 'content_bin' : 'content')
  91. . ', link, date, `lastSeen`, hash, is_read, is_favorite, id_feed, tags, attributes) '
  92. . 'VALUES(:id, :guid, :title, :author, '
  93. . (static::isCompressed() ? 'COMPRESS(:content)' : ':content')
  94. . ', :link, :date, :last_seen, '
  95. . static::sqlHexDecode(':hash')
  96. . ', :is_read, :is_favorite, :id_feed, :tags, :attributes)');
  97. $this->addEntryPrepared = $this->pdo->prepare($sql);
  98. }
  99. if ($this->addEntryPrepared) {
  100. $this->addEntryPrepared->bindParam(':id', $valuesTmp['id']);
  101. $valuesTmp['guid'] = substr($valuesTmp['guid'], 0, 767);
  102. $valuesTmp['guid'] = safe_ascii($valuesTmp['guid']);
  103. $this->addEntryPrepared->bindParam(':guid', $valuesTmp['guid']);
  104. $valuesTmp['title'] = mb_strcut($valuesTmp['title'], 0, 8192, 'UTF-8');
  105. $valuesTmp['title'] = safe_utf8($valuesTmp['title']);
  106. $this->addEntryPrepared->bindParam(':title', $valuesTmp['title']);
  107. $valuesTmp['author'] = mb_strcut($valuesTmp['author'], 0, 1024, 'UTF-8');
  108. $valuesTmp['author'] = safe_utf8($valuesTmp['author']);
  109. $this->addEntryPrepared->bindParam(':author', $valuesTmp['author']);
  110. $valuesTmp['content'] = safe_utf8($valuesTmp['content']);
  111. $this->addEntryPrepared->bindParam(':content', $valuesTmp['content']);
  112. $valuesTmp['link'] = substr($valuesTmp['link'], 0, 16383);
  113. $valuesTmp['link'] = safe_ascii($valuesTmp['link']);
  114. $this->addEntryPrepared->bindParam(':link', $valuesTmp['link']);
  115. $this->addEntryPrepared->bindParam(':date', $valuesTmp['date'], PDO::PARAM_INT);
  116. if (empty($valuesTmp['lastSeen'])) {
  117. $valuesTmp['lastSeen'] = time();
  118. }
  119. $this->addEntryPrepared->bindParam(':last_seen', $valuesTmp['lastSeen'], PDO::PARAM_INT);
  120. $valuesTmp['is_read'] = $valuesTmp['is_read'] ? 1 : 0;
  121. $this->addEntryPrepared->bindParam(':is_read', $valuesTmp['is_read'], PDO::PARAM_INT);
  122. $valuesTmp['is_favorite'] = $valuesTmp['is_favorite'] ? 1 : 0;
  123. $this->addEntryPrepared->bindParam(':is_favorite', $valuesTmp['is_favorite'], PDO::PARAM_INT);
  124. $this->addEntryPrepared->bindParam(':id_feed', $valuesTmp['id_feed'], PDO::PARAM_INT);
  125. $valuesTmp['tags'] = mb_strcut($valuesTmp['tags'], 0, 2048, 'UTF-8');
  126. $valuesTmp['tags'] = safe_utf8($valuesTmp['tags']);
  127. $this->addEntryPrepared->bindParam(':tags', $valuesTmp['tags']);
  128. if (!isset($valuesTmp['attributes'])) {
  129. $valuesTmp['attributes'] = [];
  130. }
  131. $this->addEntryPrepared->bindValue(':attributes', is_string($valuesTmp['attributes']) ? $valuesTmp['attributes'] :
  132. json_encode($valuesTmp['attributes'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
  133. if (static::hasNativeHex()) {
  134. $this->addEntryPrepared->bindParam(':hash', $valuesTmp['hash']);
  135. } else {
  136. $valuesTmp['hashBin'] = hex2bin($valuesTmp['hash']);
  137. $this->addEntryPrepared->bindParam(':hash', $valuesTmp['hashBin']);
  138. }
  139. }
  140. if ($this->addEntryPrepared && $this->addEntryPrepared->execute()) {
  141. return true;
  142. } else {
  143. $info = $this->addEntryPrepared == null ? $this->pdo->errorInfo() : $this->addEntryPrepared->errorInfo();
  144. if ($this->autoUpdateDb($info)) {
  145. $this->addEntryPrepared = null;
  146. return $this->addEntry($valuesTmp);
  147. } elseif ((int)((int)$info[0] / 1000) !== 23) { //Filter out "SQLSTATE Class code 23: Constraint Violation" because of expected duplicate entries
  148. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info)
  149. . ' while adding entry in feed ' . $valuesTmp['id_feed'] . ' with title: ' . $valuesTmp['title']);
  150. }
  151. return false;
  152. }
  153. }
  154. public function commitNewEntries(): bool {
  155. $sql = <<<'SQL'
  156. SET @rank=(SELECT MAX(id) - COUNT(*) FROM `_entrytmp`);
  157. INSERT IGNORE INTO `_entry` (
  158. id, guid, title, author, content_bin, link, date, `lastSeen`,
  159. hash, is_read, is_favorite, id_feed, tags, attributes
  160. )
  161. SELECT @rank:=@rank+1 AS id, guid, title, author, content_bin, link, date, `lastSeen`, hash, is_read, is_favorite, id_feed, tags, attributes
  162. FROM `_entrytmp`
  163. ORDER BY date, id;
  164. DELETE FROM `_entrytmp` WHERE id <= @rank;
  165. SQL;
  166. $hadTransaction = $this->pdo->inTransaction();
  167. if (!$hadTransaction) {
  168. $this->pdo->beginTransaction();
  169. }
  170. $result = $this->pdo->exec($sql) !== false;
  171. if (!$hadTransaction) {
  172. $this->pdo->commit();
  173. }
  174. return $result;
  175. }
  176. private ?PDOStatement $updateEntryPrepared = null;
  177. /** @param array{'id':string,'guid':string,'title':string,'author':string,'content':string,'link':string,'date':int,'lastSeen':int,'hash':string,
  178. * 'is_read':bool|int|null,'is_favorite':bool|int|null,'id_feed':int,'tags':string,'attributes':array<string,mixed>} $valuesTmp */
  179. public function updateEntry(array $valuesTmp): bool {
  180. if (!isset($valuesTmp['is_read'])) {
  181. $valuesTmp['is_read'] = null;
  182. }
  183. if (!isset($valuesTmp['is_favorite'])) {
  184. $valuesTmp['is_favorite'] = null;
  185. }
  186. if ($this->updateEntryPrepared === null) {
  187. $sql = 'UPDATE `_entry` '
  188. . 'SET title=:title, author=:author, '
  189. . (static::isCompressed() ? 'content_bin=COMPRESS(:content)' : 'content=:content')
  190. . ', link=:link, date=:date, `lastSeen`=:last_seen'
  191. . ', hash=' . static::sqlHexDecode(':hash')
  192. . ', is_read=COALESCE(:is_read, is_read)'
  193. . ', is_favorite=COALESCE(:is_favorite, is_favorite)'
  194. . ', tags=:tags, attributes=:attributes '
  195. . 'WHERE id_feed=:id_feed AND guid=:guid';
  196. $this->updateEntryPrepared = $this->pdo->prepare($sql) ?: null;
  197. }
  198. if ($this->updateEntryPrepared) {
  199. $valuesTmp['guid'] = substr($valuesTmp['guid'], 0, 767);
  200. $valuesTmp['guid'] = safe_ascii($valuesTmp['guid']);
  201. $this->updateEntryPrepared->bindParam(':guid', $valuesTmp['guid']);
  202. $valuesTmp['title'] = mb_strcut($valuesTmp['title'], 0, 8192, 'UTF-8');
  203. $valuesTmp['title'] = safe_utf8($valuesTmp['title']);
  204. $this->updateEntryPrepared->bindParam(':title', $valuesTmp['title']);
  205. $valuesTmp['author'] = mb_strcut($valuesTmp['author'], 0, 1024, 'UTF-8');
  206. $valuesTmp['author'] = safe_utf8($valuesTmp['author']);
  207. $this->updateEntryPrepared->bindParam(':author', $valuesTmp['author']);
  208. $valuesTmp['content'] = safe_utf8($valuesTmp['content']);
  209. $this->updateEntryPrepared->bindParam(':content', $valuesTmp['content']);
  210. $valuesTmp['link'] = substr($valuesTmp['link'], 0, 16383);
  211. $valuesTmp['link'] = safe_ascii($valuesTmp['link']);
  212. $this->updateEntryPrepared->bindParam(':link', $valuesTmp['link']);
  213. $this->updateEntryPrepared->bindParam(':date', $valuesTmp['date'], PDO::PARAM_INT);
  214. $this->updateEntryPrepared->bindParam(':last_seen', $valuesTmp['lastSeen'], PDO::PARAM_INT);
  215. if ($valuesTmp['is_read'] === null) {
  216. $this->updateEntryPrepared->bindValue(':is_read', null, PDO::PARAM_NULL);
  217. } else {
  218. $this->updateEntryPrepared->bindValue(':is_read', $valuesTmp['is_read'] ? 1 : 0, PDO::PARAM_INT);
  219. }
  220. if ($valuesTmp['is_favorite'] === null) {
  221. $this->updateEntryPrepared->bindValue(':is_favorite', null, PDO::PARAM_NULL);
  222. } else {
  223. $this->updateEntryPrepared->bindValue(':is_favorite', $valuesTmp['is_favorite'] ? 1 : 0, PDO::PARAM_INT);
  224. }
  225. $this->updateEntryPrepared->bindParam(':id_feed', $valuesTmp['id_feed'], PDO::PARAM_INT);
  226. $valuesTmp['tags'] = mb_strcut($valuesTmp['tags'], 0, 2048, 'UTF-8');
  227. $valuesTmp['tags'] = safe_utf8($valuesTmp['tags']);
  228. $this->updateEntryPrepared->bindParam(':tags', $valuesTmp['tags']);
  229. if (!isset($valuesTmp['attributes'])) {
  230. $valuesTmp['attributes'] = [];
  231. }
  232. $this->updateEntryPrepared->bindValue(':attributes', is_string($valuesTmp['attributes']) ? $valuesTmp['attributes'] :
  233. json_encode($valuesTmp['attributes'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
  234. if (static::hasNativeHex()) {
  235. $this->updateEntryPrepared->bindParam(':hash', $valuesTmp['hash']);
  236. } else {
  237. $valuesTmp['hashBin'] = hex2bin($valuesTmp['hash']);
  238. $this->updateEntryPrepared->bindParam(':hash', $valuesTmp['hashBin']);
  239. }
  240. }
  241. if ($this->updateEntryPrepared && $this->updateEntryPrepared->execute()) {
  242. return true;
  243. } else {
  244. $info = $this->updateEntryPrepared == null ? $this->pdo->errorInfo() : $this->updateEntryPrepared->errorInfo();
  245. if ($this->autoUpdateDb($info)) {
  246. return $this->updateEntry($valuesTmp);
  247. }
  248. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info)
  249. . ' while updating entry with GUID ' . $valuesTmp['guid'] . ' in feed ' . $valuesTmp['id_feed']);
  250. return false;
  251. }
  252. }
  253. /**
  254. * Count the number of new entries in the temporary table (which have not yet been committed).
  255. */
  256. public function countNewEntries(): int {
  257. $sql = <<<'SQL'
  258. SELECT COUNT(id) AS nb_entries FROM `_entrytmp`
  259. SQL;
  260. $res = $this->fetchColumn($sql, 0);
  261. return isset($res[0]) ? (int)$res[0] : -1;
  262. }
  263. /**
  264. * Toggle favorite marker on one or more article
  265. *
  266. * @todo simplify the query by removing the str_repeat. I am pretty sure
  267. * there is an other way to do that.
  268. *
  269. * @param numeric-string|array<numeric-string> $ids
  270. * @return int|false
  271. */
  272. public function markFavorite($ids, bool $is_favorite = true) {
  273. if (!is_array($ids)) {
  274. $ids = [$ids];
  275. }
  276. if (count($ids) < 1) {
  277. return 0;
  278. }
  279. FreshRSS_UserDAO::touch();
  280. if (count($ids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  281. // Split a query with too many variables parameters
  282. $affected = 0;
  283. $idsChunks = array_chunk($ids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  284. foreach ($idsChunks as $idsChunk) {
  285. $affected += ($this->markFavorite($idsChunk, $is_favorite) ?: 0);
  286. }
  287. return $affected;
  288. }
  289. $sql = 'UPDATE `_entry` '
  290. . 'SET is_favorite=? '
  291. . 'WHERE id IN (' . str_repeat('?,', count($ids) - 1) . '?)';
  292. $values = [$is_favorite ? 1 : 0];
  293. $values = array_merge($values, $ids);
  294. $stm = $this->pdo->prepare($sql);
  295. if ($stm !== false && $stm->execute($values)) {
  296. return $stm->rowCount();
  297. } else {
  298. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  299. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  300. return false;
  301. }
  302. }
  303. /**
  304. * Update the unread article cache held on every feed details.
  305. * Depending on the parameters, it updates the cache on one feed, on all
  306. * feeds from one category or on all feeds.
  307. */
  308. protected function updateCacheUnreads(?int $catId = null, ?int $feedId = null): bool {
  309. // Help MySQL/MariaDB's optimizer with the query plan:
  310. $useIndex = $this->pdo->dbType() === 'mysql' ? 'USE INDEX (entry_feed_read_index)' : '';
  311. $sql = <<<SQL
  312. UPDATE `_feed`
  313. SET `cache_nbUnreads`=(
  314. SELECT COUNT(*) AS nbUnreads FROM `_entry` e {$useIndex}
  315. WHERE e.id_feed=`_feed`.id AND e.is_read=0)
  316. SQL;
  317. $hasWhere = false;
  318. $values = [];
  319. if ($feedId != null) {
  320. $sql .= ' WHERE';
  321. $hasWhere = true;
  322. $sql .= ' id=?';
  323. $values[] = $feedId;
  324. }
  325. if ($catId != null) {
  326. $sql .= $hasWhere ? ' AND' : ' WHERE';
  327. $hasWhere = true;
  328. $sql .= ' category=?';
  329. $values[] = $catId;
  330. }
  331. $stm = $this->pdo->prepare($sql);
  332. if ($stm !== false && $stm->execute($values)) {
  333. return true;
  334. } else {
  335. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  336. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  337. return false;
  338. }
  339. }
  340. /**
  341. * Toggle the read marker on one or more article.
  342. * Then the cache is updated.
  343. *
  344. * @param numeric-string|array<numeric-string> $ids
  345. * @param bool $is_read
  346. * @return int|false affected rows
  347. */
  348. public function markRead($ids, bool $is_read = true) {
  349. if (is_array($ids)) { //Many IDs at once
  350. if (count($ids) < 6) { //Speed heuristics
  351. $affected = 0;
  352. foreach ($ids as $id) {
  353. $affected += ($this->markRead($id, $is_read) ?: 0);
  354. }
  355. return $affected;
  356. } elseif (count($ids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  357. // Split a query with too many variables parameters
  358. $affected = 0;
  359. $idsChunks = array_chunk($ids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  360. foreach ($idsChunks as $idsChunk) {
  361. $affected += ($this->markRead($idsChunk, $is_read) ?: 0);
  362. }
  363. return $affected;
  364. }
  365. FreshRSS_UserDAO::touch();
  366. $sql = 'UPDATE `_entry` '
  367. . 'SET is_read=? '
  368. . 'WHERE id IN (' . str_repeat('?,', count($ids) - 1) . '?)';
  369. $values = [$is_read ? 1 : 0];
  370. $values = array_merge($values, $ids);
  371. $stm = $this->pdo->prepare($sql);
  372. if (!($stm && $stm->execute($values))) {
  373. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  374. Minz_Log::error('SQL error ' . __METHOD__ . ' A ' . json_encode($info));
  375. return false;
  376. }
  377. $affected = $stm->rowCount();
  378. if (($affected > 0) && (!$this->updateCacheUnreads(null, null))) {
  379. return false;
  380. }
  381. return $affected;
  382. } else {
  383. FreshRSS_UserDAO::touch();
  384. $sql = 'UPDATE `_entry` e INNER JOIN `_feed` f ON e.id_feed=f.id '
  385. . 'SET e.is_read=?,'
  386. . 'f.`cache_nbUnreads`=f.`cache_nbUnreads`' . ($is_read ? '-' : '+') . '1 '
  387. . 'WHERE e.id=? AND e.is_read=?';
  388. $values = [$is_read ? 1 : 0, $ids, $is_read ? 0 : 1];
  389. $stm = $this->pdo->prepare($sql);
  390. if ($stm !== false && $stm->execute($values)) {
  391. return $stm->rowCount();
  392. } else {
  393. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  394. Minz_Log::error('SQL error ' . __METHOD__ . ' B ' . json_encode($info));
  395. return false;
  396. }
  397. }
  398. }
  399. /**
  400. * Mark all entries as read depending on parameters.
  401. * If $onlyFavorites is true, it is used when the user mark as read in
  402. * the favorite pseudo-category.
  403. * If $priorityMin is greater than 0, it is used when the user mark as
  404. * read in the main feed pseudo-category.
  405. * Then the cache is updated.
  406. *
  407. * If $idMax equals 0, a deprecated debug message is logged
  408. *
  409. * @param numeric-string $idMax fail safe article ID
  410. * @return int|false affected rows
  411. */
  412. public function markReadEntries(string $idMax = '0', bool $onlyFavorites = false, ?int $priorityMin = null, ?int $prioritMax = null,
  413. ?FreshRSS_BooleanSearch $filters = null, int $state = 0, bool $is_read = true) {
  414. FreshRSS_UserDAO::touch();
  415. if ($idMax == '0') {
  416. $idMax = time() . '000000';
  417. Minz_Log::debug('Calling markReadEntries(0) is deprecated!');
  418. }
  419. $sql = 'UPDATE `_entry` SET is_read = ? WHERE is_read <> ? AND id <= ?';
  420. $values = [$is_read ? 1 : 0, $is_read ? 1 : 0, $idMax];
  421. if ($onlyFavorites) {
  422. $sql .= ' AND is_favorite=1';
  423. }
  424. if ($priorityMin !== null || $prioritMax !== null) {
  425. $sql .= ' AND id_feed IN (SELECT f.id FROM `_feed` f WHERE 1=1';
  426. if ($priorityMin !== null) {
  427. $sql .= ' AND f.priority >= ?';
  428. $values[] = $priorityMin;
  429. }
  430. if ($prioritMax !== null) {
  431. $sql .= ' AND f.priority < ?';
  432. $values[] = $prioritMax;
  433. }
  434. $sql .= ')';
  435. }
  436. [$searchValues, $search] = $this->sqlListEntriesWhere('', $filters, $state);
  437. $stm = $this->pdo->prepare($sql . $search);
  438. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  439. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  440. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  441. return false;
  442. }
  443. $affected = $stm->rowCount();
  444. if (($affected > 0) && (!$this->updateCacheUnreads(null, null))) {
  445. return false;
  446. }
  447. return $affected;
  448. }
  449. /**
  450. * Mark all the articles in a category as read.
  451. * There is a fail safe to prevent to mark as read articles that are
  452. * loaded during the mark as read action. Then the cache is updated.
  453. *
  454. * If $idMax equals 0, a deprecated debug message is logged
  455. *
  456. * @param int $id category ID
  457. * @param numeric-string $idMax fail safe article ID
  458. * @return int|false affected rows
  459. */
  460. public function markReadCat(int $id, string $idMax = '0', ?FreshRSS_BooleanSearch $filters = null, int $state = 0, bool $is_read = true) {
  461. FreshRSS_UserDAO::touch();
  462. if ($idMax == '0') {
  463. $idMax = time() . '000000';
  464. Minz_Log::debug('Calling markReadCat(0) is deprecated!');
  465. }
  466. $sql = <<<'SQL'
  467. UPDATE `_entry`
  468. SET is_read = ?
  469. WHERE is_read <> ? AND id <= ?
  470. AND id_feed IN (SELECT f.id FROM `_feed` f WHERE f.category=?)
  471. SQL;
  472. $values = [$is_read ? 1 : 0, $is_read ? 1 : 0, $idMax, $id];
  473. [$searchValues, $search] = $this->sqlListEntriesWhere('', $filters, $state);
  474. $stm = $this->pdo->prepare($sql . $search);
  475. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  476. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  477. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  478. return false;
  479. }
  480. $affected = $stm->rowCount();
  481. if (($affected > 0) && (!$this->updateCacheUnreads($id, null))) {
  482. return false;
  483. }
  484. return $affected;
  485. }
  486. /**
  487. * Mark all the articles in a feed as read.
  488. * There is a fail safe to prevent to mark as read articles that are
  489. * loaded during the mark as read action. Then the cache is updated.
  490. *
  491. * If $idMax equals 0, a deprecated debug message is logged
  492. *
  493. * @param int $id_feed feed ID
  494. * @param numeric-string $idMax fail safe article ID
  495. * @return int|false affected rows
  496. */
  497. public function markReadFeed(int $id_feed, string $idMax = '0', ?FreshRSS_BooleanSearch $filters = null, int $state = 0, bool $is_read = true) {
  498. FreshRSS_UserDAO::touch();
  499. if ($idMax == '0') {
  500. $idMax = time() . '000000';
  501. Minz_Log::debug('Calling markReadFeed(0) is deprecated!');
  502. }
  503. $hadTransaction = $this->pdo->inTransaction();
  504. if (!$hadTransaction) {
  505. $this->pdo->beginTransaction();
  506. }
  507. $sql = 'UPDATE `_entry` '
  508. . 'SET is_read=? '
  509. . 'WHERE id_feed=? AND is_read <> ? AND id <= ?';
  510. $values = [$is_read ? 1 : 0, $id_feed, $is_read ? 1 : 0, $idMax];
  511. [$searchValues, $search] = $this->sqlListEntriesWhere('', $filters, $state);
  512. $stm = $this->pdo->prepare($sql . $search);
  513. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  514. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  515. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info) . ' with SQL: ' . $sql . $search);
  516. $this->pdo->rollBack();
  517. return false;
  518. }
  519. $affected = $stm->rowCount();
  520. if ($affected > 0) {
  521. $sql = 'UPDATE `_feed` '
  522. . 'SET `cache_nbUnreads`=`cache_nbUnreads`-' . $affected
  523. . ' WHERE id=:id';
  524. $stm = $this->pdo->prepare($sql);
  525. if (!($stm !== false &&
  526. $stm->bindParam(':id', $id_feed, PDO::PARAM_INT) &&
  527. $stm->execute())) {
  528. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  529. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  530. $this->pdo->rollBack();
  531. return false;
  532. }
  533. }
  534. if (!$hadTransaction) {
  535. $this->pdo->commit();
  536. }
  537. return $affected;
  538. }
  539. /**
  540. * Mark all the articles in a tag as read.
  541. * @param int $id tag ID, or empty for targeting any tag
  542. * @param numeric-string $idMax max article ID
  543. * @return int|false affected rows
  544. */
  545. public function markReadTag(int $id = 0, string $idMax = '0', ?FreshRSS_BooleanSearch $filters = null,
  546. int $state = 0, bool $is_read = true) {
  547. FreshRSS_UserDAO::touch();
  548. if ($idMax == '0') {
  549. $idMax = time() . '000000';
  550. Minz_Log::debug('Calling markReadTag(0) is deprecated!');
  551. }
  552. $sql = 'UPDATE `_entry` e INNER JOIN `_entrytag` et ON et.id_entry = e.id '
  553. . 'SET e.is_read = ? '
  554. . 'WHERE '
  555. . ($id == 0 ? '' : 'et.id_tag = ? AND ')
  556. . 'e.is_read <> ? AND e.id <= ?';
  557. $values = [$is_read ? 1 : 0];
  558. if ($id != 0) {
  559. $values[] = $id;
  560. }
  561. $values[] = $is_read ? 1 : 0;
  562. $values[] = $idMax;
  563. [$searchValues, $search] = $this->sqlListEntriesWhere('e.', $filters, $state);
  564. $stm = $this->pdo->prepare($sql . $search);
  565. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  566. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  567. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  568. return false;
  569. }
  570. $affected = $stm->rowCount();
  571. if (($affected > 0) && (!$this->updateCacheUnreads(null, null))) {
  572. return false;
  573. }
  574. return $affected;
  575. }
  576. /**
  577. * Remember to call updateCachedValues($id_feed) or updateCachedValues() just after.
  578. * @param array<string,bool|int|string> $options
  579. * @return int|false
  580. */
  581. public function cleanOldEntries(int $id_feed, array $options = []) {
  582. $sql = 'DELETE FROM `_entry` WHERE id_feed = :id_feed1'; //No alias for MySQL / MariaDB
  583. $params = [];
  584. $params[':id_feed1'] = $id_feed;
  585. //==Exclusions==
  586. if (!empty($options['keep_favourites'])) {
  587. $sql .= ' AND is_favorite = 0';
  588. }
  589. if (!empty($options['keep_unreads'])) {
  590. $sql .= ' AND is_read = 1';
  591. }
  592. if (!empty($options['keep_labels'])) {
  593. $sql .= ' AND NOT EXISTS (SELECT 1 FROM `_entrytag` WHERE id_entry = id)';
  594. }
  595. if (!empty($options['keep_min']) && $options['keep_min'] > 0) {
  596. //Double SELECT for MySQL workaround ERROR 1093 (HY000)
  597. $sql .= ' AND `lastSeen` < (SELECT `lastSeen`'
  598. . ' FROM (SELECT e2.`lastSeen` FROM `_entry` e2 WHERE e2.id_feed = :id_feed2'
  599. . ' ORDER BY e2.`lastSeen` DESC LIMIT 1 OFFSET :keep_min) last_seen2)';
  600. $params[':id_feed2'] = $id_feed;
  601. $params[':keep_min'] = (int)$options['keep_min'];
  602. }
  603. //Keep at least the articles seen at the last refresh
  604. $sql .= ' AND `lastSeen` < (SELECT maxlastseen'
  605. . ' FROM (SELECT MAX(e3.`lastSeen`) AS maxlastseen FROM `_entry` e3 WHERE e3.id_feed = :id_feed3) last_seen3)';
  606. $params[':id_feed3'] = $id_feed;
  607. //==Inclusions==
  608. $sql .= ' AND (1=0';
  609. if (!empty($options['keep_period']) && is_string($options['keep_period'])) {
  610. $sql .= ' OR `lastSeen` < :max_last_seen';
  611. $now = new DateTime('now');
  612. $now->sub(new DateInterval($options['keep_period']));
  613. $params[':max_last_seen'] = $now->format('U');
  614. }
  615. if (!empty($options['keep_max']) && $options['keep_max'] > 0) {
  616. $sql .= ' OR `lastSeen` <= (SELECT `lastSeen`'
  617. . ' FROM (SELECT e4.`lastSeen` FROM `_entry` e4 WHERE e4.id_feed = :id_feed4'
  618. . ' ORDER BY e4.`lastSeen` DESC LIMIT 1 OFFSET :keep_max) last_seen4)';
  619. $params[':id_feed4'] = $id_feed;
  620. $params[':keep_max'] = (int)$options['keep_max'];
  621. }
  622. $sql .= ')';
  623. $stm = $this->pdo->prepare($sql);
  624. if ($stm !== false && $stm->execute($params)) {
  625. return $stm->rowCount();
  626. } else {
  627. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  628. if ($this->autoUpdateDb($info)) {
  629. return $this->cleanOldEntries($id_feed, $options);
  630. }
  631. Minz_Log::error(__method__ . ' error:' . json_encode($info));
  632. return false;
  633. }
  634. }
  635. /** @return Traversable<array{'id':string,'guid':string,'title':string,'author':string,'content':string,'link':string,'date':int,'lastSeen':int,
  636. * 'hash':string,'is_read':bool,'is_favorite':bool,'id_feed':int,'tags':string,'attributes':?string}> */
  637. public function selectAll(?int $limit = null): Traversable {
  638. $content = static::isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content';
  639. $hash = static::sqlHexEncode('hash');
  640. $sql = <<<SQL
  641. SELECT id, guid, title, author, {$content}, link, date, `lastSeen`, {$hash} AS hash, is_read, is_favorite, id_feed, tags, attributes
  642. FROM `_entry`
  643. SQL;
  644. if (is_int($limit) && $limit >= 0) {
  645. $sql .= ' ORDER BY id DESC LIMIT ' . $limit;
  646. }
  647. $stm = $this->pdo->query($sql);
  648. if ($stm != false) {
  649. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  650. /** @var array{'id':string,'guid':string,'title':string,'author':string,'content':string,'link':string,'date':int,'lastSeen':int,
  651. * 'hash':string,'is_read':bool,'is_favorite':bool,'id_feed':int,'tags':string,'attributes':?string} $row */
  652. yield $row;
  653. }
  654. } else {
  655. $info = $this->pdo->errorInfo();
  656. if ($this->autoUpdateDb($info)) {
  657. yield from $this->selectAll();
  658. } else {
  659. Minz_Log::error(__method__ . ' error: ' . json_encode($info));
  660. }
  661. }
  662. }
  663. public function searchByGuid(int $id_feed, string $guid): ?FreshRSS_Entry {
  664. $content = static::isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content';
  665. $hash = static::sqlHexEncode('hash');
  666. $sql = <<<SQL
  667. SELECT id, guid, title, author, link, date, is_read, is_favorite, {$hash} AS hash, id_feed, tags, attributes, {$content}
  668. FROM `_entry` WHERE id_feed=:id_feed AND guid=:guid
  669. SQL;
  670. $res = $this->fetchAssoc($sql, [':id_feed' => $id_feed, ':guid' => $guid]);
  671. /** @var array<array{'id':string,'id_feed':int,'guid':string,'title':string,'author':string,'content':string,'link':string,'date':int,
  672. * 'is_read':int,'is_favorite':int,'tags':string,'attributes':?string}> $res */
  673. return isset($res[0]) ? FreshRSS_Entry::fromArray($res[0]) : null;
  674. }
  675. public function searchById(string $id): ?FreshRSS_Entry {
  676. $content = static::isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content';
  677. $hash = static::sqlHexEncode('hash');
  678. $sql = <<<SQL
  679. SELECT id, guid, title, author, link, date, is_read, is_favorite, {$hash} AS hash, id_feed, tags, attributes, {$content}
  680. FROM `_entry` WHERE id=:id
  681. SQL;
  682. $res = $this->fetchAssoc($sql, [':id' => $id]);
  683. /** @var array<array{'id':string,'id_feed':int,'guid':string,'title':string,'author':string,'content':string,'link':string,'date':int,
  684. * 'is_read':int,'is_favorite':int,'tags':string,'attributes':?string}> $res */
  685. return isset($res[0]) ? FreshRSS_Entry::fromArray($res[0]) : null;
  686. }
  687. public function searchIdByGuid(int $id_feed, string $guid): ?string {
  688. $sql = 'SELECT id FROM `_entry` WHERE id_feed=:id_feed AND guid=:guid';
  689. $res = $this->fetchColumn($sql, 0, [':id_feed' => $id_feed, ':guid' => $guid]);
  690. return empty($res[0]) ? null : (string)($res[0]);
  691. }
  692. /** @return array{0:array<int|string>,1:string} */
  693. public static function sqlBooleanSearch(string $alias, FreshRSS_BooleanSearch $filters, int $level = 0): array {
  694. $search = '';
  695. $values = [];
  696. $isOpen = false;
  697. foreach ($filters->searches() as $filter) {
  698. if ($filter == null) {
  699. continue;
  700. }
  701. if ($filter instanceof FreshRSS_BooleanSearch) {
  702. // BooleanSearches are combined by AND (default) or OR (special case) operator and are recursive
  703. [$filterValues, $filterSearch] = self::sqlBooleanSearch($alias, $filter, $level + 1);
  704. $filterSearch = trim($filterSearch);
  705. if ($filterSearch !== '') {
  706. if ($search !== '') {
  707. $search .= $filter->operator();
  708. } elseif (in_array($filter->operator(), ['AND NOT', 'OR NOT'], true)) {
  709. // Special case if we start with a negation (there is already the default AND before)
  710. $search .= ' NOT';
  711. }
  712. $search .= ' (' . $filterSearch . ') ';
  713. $values = array_merge($values, $filterValues);
  714. }
  715. continue;
  716. }
  717. // Searches are combined by OR and are not recursive
  718. $sub_search = '';
  719. if ($filter->getEntryIds() !== null) {
  720. $sub_search .= 'AND ' . $alias . 'id IN (';
  721. foreach ($filter->getEntryIds() as $entry_id) {
  722. $sub_search .= '?,';
  723. $values[] = $entry_id;
  724. }
  725. $sub_search = rtrim($sub_search, ',');
  726. $sub_search .= ') ';
  727. }
  728. if ($filter->getNotEntryIds() !== null) {
  729. $sub_search .= 'AND ' . $alias . 'id NOT IN (';
  730. foreach ($filter->getNotEntryIds() as $entry_id) {
  731. $sub_search .= '?,';
  732. $values[] = $entry_id;
  733. }
  734. $sub_search = rtrim($sub_search, ',');
  735. $sub_search .= ') ';
  736. }
  737. if ($filter->getMinDate() !== null) {
  738. $sub_search .= 'AND ' . $alias . 'id >= ? ';
  739. $values[] = "{$filter->getMinDate()}000000";
  740. }
  741. if ($filter->getMaxDate() !== null) {
  742. $sub_search .= 'AND ' . $alias . 'id <= ? ';
  743. $values[] = "{$filter->getMaxDate()}000000";
  744. }
  745. if ($filter->getMinPubdate() !== null) {
  746. $sub_search .= 'AND ' . $alias . 'date >= ? ';
  747. $values[] = $filter->getMinPubdate();
  748. }
  749. if ($filter->getMaxPubdate() !== null) {
  750. $sub_search .= 'AND ' . $alias . 'date <= ? ';
  751. $values[] = $filter->getMaxPubdate();
  752. }
  753. //Negation of date intervals must be combined by OR
  754. if ($filter->getNotMinDate() !== null || $filter->getNotMaxDate() !== null) {
  755. $sub_search .= 'AND (';
  756. if ($filter->getNotMinDate() !== null) {
  757. $sub_search .= $alias . 'id < ?';
  758. $values[] = "{$filter->getNotMinDate()}000000";
  759. if ($filter->getNotMaxDate()) {
  760. $sub_search .= ' OR ';
  761. }
  762. }
  763. if ($filter->getNotMaxDate() !== null) {
  764. $sub_search .= $alias . 'id > ?';
  765. $values[] = "{$filter->getNotMaxDate()}000000";
  766. }
  767. $sub_search .= ') ';
  768. }
  769. if ($filter->getNotMinPubdate() !== null || $filter->getNotMaxPubdate() !== null) {
  770. $sub_search .= 'AND (';
  771. if ($filter->getNotMinPubdate() !== null) {
  772. $sub_search .= $alias . 'date < ?';
  773. $values[] = $filter->getNotMinPubdate();
  774. if ($filter->getNotMaxPubdate()) {
  775. $sub_search .= ' OR ';
  776. }
  777. }
  778. if ($filter->getNotMaxPubdate() !== null) {
  779. $sub_search .= $alias . 'date > ?';
  780. $values[] = $filter->getNotMaxPubdate();
  781. }
  782. $sub_search .= ') ';
  783. }
  784. if ($filter->getFeedIds() !== null) {
  785. $sub_search .= 'AND ' . $alias . 'id_feed IN (';
  786. foreach ($filter->getFeedIds() as $feed_id) {
  787. $sub_search .= '?,';
  788. $values[] = $feed_id;
  789. }
  790. $sub_search = rtrim($sub_search, ',');
  791. $sub_search .= ') ';
  792. }
  793. if ($filter->getNotFeedIds() !== null) {
  794. $sub_search .= 'AND ' . $alias . 'id_feed NOT IN (';
  795. foreach ($filter->getNotFeedIds() as $feed_id) {
  796. $sub_search .= '?,';
  797. $values[] = $feed_id;
  798. }
  799. $sub_search = rtrim($sub_search, ',');
  800. $sub_search .= ') ';
  801. }
  802. if ($filter->getLabelIds() !== null) {
  803. if ($filter->getLabelIds() === '*') {
  804. $sub_search .= 'AND EXISTS (SELECT et.id_tag FROM `_entrytag` et WHERE et.id_entry = ' . $alias . 'id) ';
  805. } else {
  806. $sub_search .= 'AND ' . $alias . 'id IN (SELECT et.id_entry FROM `_entrytag` et WHERE et.id_tag IN (';
  807. foreach ($filter->getLabelIds() as $label_id) {
  808. $sub_search .= '?,';
  809. $values[] = $label_id;
  810. }
  811. $sub_search = rtrim($sub_search, ',');
  812. $sub_search .= ')) ';
  813. }
  814. }
  815. if ($filter->getNotLabelIds() !== null) {
  816. if ($filter->getNotLabelIds() === '*') {
  817. $sub_search .= 'AND NOT EXISTS (SELECT et.id_tag FROM `_entrytag` et WHERE et.id_entry = ' . $alias . 'id) ';
  818. } else {
  819. $sub_search .= 'AND ' . $alias . 'id NOT IN (SELECT et.id_entry FROM `_entrytag` et WHERE et.id_tag IN (';
  820. foreach ($filter->getNotLabelIds() as $label_id) {
  821. $sub_search .= '?,';
  822. $values[] = $label_id;
  823. }
  824. $sub_search = rtrim($sub_search, ',');
  825. $sub_search .= ')) ';
  826. }
  827. }
  828. if ($filter->getLabelNames() !== null) {
  829. $sub_search .= 'AND ' . $alias . 'id IN (SELECT et.id_entry FROM `_entrytag` et, `_tag` t WHERE et.id_tag = t.id AND t.name IN (';
  830. foreach ($filter->getLabelNames() as $label_name) {
  831. $sub_search .= '?,';
  832. $values[] = $label_name;
  833. }
  834. $sub_search = rtrim($sub_search, ',');
  835. $sub_search .= ')) ';
  836. }
  837. if ($filter->getNotLabelNames() !== null) {
  838. $sub_search .= 'AND ' . $alias . 'id NOT IN (SELECT et.id_entry FROM `_entrytag` et, `_tag` t WHERE et.id_tag = t.id AND t.name IN (';
  839. foreach ($filter->getNotLabelNames() as $label_name) {
  840. $sub_search .= '?,';
  841. $values[] = $label_name;
  842. }
  843. $sub_search = rtrim($sub_search, ',');
  844. $sub_search .= ')) ';
  845. }
  846. if ($filter->getAuthor() !== null) {
  847. foreach ($filter->getAuthor() as $author) {
  848. $sub_search .= 'AND ' . $alias . 'author LIKE ? ';
  849. $values[] = "%{$author}%";
  850. }
  851. }
  852. if ($filter->getIntitle() !== null) {
  853. foreach ($filter->getIntitle() as $title) {
  854. $sub_search .= 'AND ' . $alias . 'title LIKE ? ';
  855. $values[] = "%{$title}%";
  856. }
  857. }
  858. if ($filter->getTags() !== null) {
  859. foreach ($filter->getTags() as $tag) {
  860. $sub_search .= 'AND ' . static::sqlConcat('TRIM(' . $alias . 'tags) ', " ' #'") . ' LIKE ? ';
  861. $values[] = "%{$tag} #%";
  862. }
  863. }
  864. if ($filter->getInurl() !== null) {
  865. foreach ($filter->getInurl() as $url) {
  866. $sub_search .= 'AND ' . $alias . 'link LIKE ? ';
  867. $values[] = "%{$url}%";
  868. }
  869. }
  870. if ($filter->getNotAuthor() !== null) {
  871. foreach ($filter->getNotAuthor() as $author) {
  872. $sub_search .= 'AND ' . $alias . 'author NOT LIKE ? ';
  873. $values[] = "%{$author}%";
  874. }
  875. }
  876. if ($filter->getNotIntitle() !== null) {
  877. foreach ($filter->getNotIntitle() as $title) {
  878. $sub_search .= 'AND ' . $alias . 'title NOT LIKE ? ';
  879. $values[] = "%{$title}%";
  880. }
  881. }
  882. if ($filter->getNotTags() !== null) {
  883. foreach ($filter->getNotTags() as $tag) {
  884. $sub_search .= 'AND ' . static::sqlConcat('TRIM(' . $alias . 'tags) ', " ' #'") . ' NOT LIKE ? ';
  885. $values[] = "%{$tag} #%";
  886. }
  887. }
  888. if ($filter->getNotInurl() !== null) {
  889. foreach ($filter->getNotInurl() as $url) {
  890. $sub_search .= 'AND ' . $alias . 'link NOT LIKE ? ';
  891. $values[] = "%{$url}%";
  892. }
  893. }
  894. if ($filter->getSearch() !== null) {
  895. foreach ($filter->getSearch() as $search_value) {
  896. if (static::isCompressed()) { // MySQL-only
  897. $sub_search .= 'AND CONCAT(' . $alias . 'title, UNCOMPRESS(' . $alias . 'content_bin)) LIKE ? ';
  898. $values[] = "%{$search_value}%";
  899. } else {
  900. $sub_search .= 'AND (' . $alias . 'title LIKE ? OR ' . $alias . 'content LIKE ?) ';
  901. $values[] = "%{$search_value}%";
  902. $values[] = "%{$search_value}%";
  903. }
  904. }
  905. }
  906. if ($filter->getNotSearch() !== null) {
  907. foreach ($filter->getNotSearch() as $search_value) {
  908. if (static::isCompressed()) { // MySQL-only
  909. $sub_search .= 'AND CONCAT(' . $alias . 'title, UNCOMPRESS(' . $alias . 'content_bin)) NOT LIKE ? ';
  910. $values[] = "%{$search_value}%";
  911. } else {
  912. $sub_search .= 'AND ' . $alias . 'title NOT LIKE ? AND ' . $alias . 'content NOT LIKE ? ';
  913. $values[] = "%{$search_value}%";
  914. $values[] = "%{$search_value}%";
  915. }
  916. }
  917. }
  918. if ($sub_search != '') {
  919. if ($isOpen) {
  920. $search .= ' OR ';
  921. } else {
  922. $isOpen = true;
  923. }
  924. // Remove superfluous leading 'AND '
  925. $search .= '(' . substr($sub_search, 4) . ')';
  926. }
  927. }
  928. return [ $values, $search ];
  929. }
  930. /**
  931. * @param 'ASC'|'DESC' $order
  932. * @return array{0:array<int|string>,1:string}
  933. * @throws FreshRSS_EntriesGetter_Exception
  934. */
  935. protected function sqlListEntriesWhere(string $alias = '', ?FreshRSS_BooleanSearch $filters = null,
  936. int $state = FreshRSS_Entry::STATE_ALL,
  937. string $order = 'DESC', string $firstId = '', int $date_min = 0): array {
  938. $search = ' ';
  939. $values = [];
  940. if ($state & FreshRSS_Entry::STATE_NOT_READ) {
  941. if (!($state & FreshRSS_Entry::STATE_READ)) {
  942. $search .= 'AND ' . $alias . 'is_read=0 ';
  943. }
  944. } elseif ($state & FreshRSS_Entry::STATE_READ) {
  945. $search .= 'AND ' . $alias . 'is_read=1 ';
  946. }
  947. if ($state & FreshRSS_Entry::STATE_FAVORITE) {
  948. if (!($state & FreshRSS_Entry::STATE_NOT_FAVORITE)) {
  949. $search .= 'AND ' . $alias . 'is_favorite=1 ';
  950. }
  951. } elseif ($state & FreshRSS_Entry::STATE_NOT_FAVORITE) {
  952. $search .= 'AND ' . $alias . 'is_favorite=0 ';
  953. }
  954. switch ($order) {
  955. case 'DESC':
  956. case 'ASC':
  957. break;
  958. default:
  959. throw new FreshRSS_EntriesGetter_Exception('Bad order in Entry->listByType: [' . $order . ']!');
  960. }
  961. if ($firstId !== '') {
  962. $search .= 'AND ' . $alias . 'id ' . ($order === 'DESC' ? '<=' : '>=') . ' ? ';
  963. $values[] = $firstId;
  964. }
  965. if ($date_min > 0) {
  966. $search .= 'AND ' . $alias . 'id >= ? ';
  967. $values[] = $date_min . '000000';
  968. }
  969. if ($filters && count($filters->searches()) > 0) {
  970. [$filterValues, $filterSearch] = self::sqlBooleanSearch($alias, $filters);
  971. $filterSearch = trim($filterSearch);
  972. if ($filterSearch !== '') {
  973. $search .= 'AND (' . $filterSearch . ') ';
  974. $values = array_merge($values, $filterValues);
  975. }
  976. }
  977. return [$values, $search];
  978. }
  979. /**
  980. * @phpstan-param 'a'|'A'|'i'|'s'|'S'|'c'|'f'|'t'|'T'|'ST' $type
  981. * @param int $id category/feed/tag ID
  982. * @param 'ASC'|'DESC' $order
  983. * @return array{0:array<int|string>,1:string}
  984. * @throws FreshRSS_EntriesGetter_Exception
  985. */
  986. private function sqlListWhere(string $type = 'a', int $id = 0, int $state = FreshRSS_Entry::STATE_ALL,
  987. string $order = 'DESC', int $limit = 1, int $offset = 0, string $firstId = '', ?FreshRSS_BooleanSearch $filters = null,
  988. int $date_min = 0): array {
  989. if (!$state) {
  990. $state = FreshRSS_Entry::STATE_ALL;
  991. }
  992. $where = '';
  993. $values = [];
  994. switch ($type) {
  995. case 'a': //All PRIORITY_MAIN_STREAM
  996. $where .= 'f.priority >= ' . FreshRSS_Feed::PRIORITY_MAIN_STREAM . ' ';
  997. break;
  998. case 'A': //All except PRIORITY_ARCHIVED
  999. $where .= 'f.priority > ' . FreshRSS_Feed::PRIORITY_ARCHIVED . ' ';
  1000. break;
  1001. case 'i': //Priority important feeds
  1002. $where .= 'f.priority >= ' . FreshRSS_Feed::PRIORITY_IMPORTANT . ' ';
  1003. break;
  1004. case 's': //Starred. Deprecated: use $state instead
  1005. $where .= 'f.priority > ' . FreshRSS_Feed::PRIORITY_ARCHIVED . ' ';
  1006. $where .= 'AND e.is_favorite=1 ';
  1007. break;
  1008. case 'S': //Starred
  1009. $where .= 'e.is_favorite=1 ';
  1010. break;
  1011. case 'c': //Category
  1012. $where .= 'f.priority >= ' . FreshRSS_Feed::PRIORITY_CATEGORY . ' ';
  1013. $where .= 'AND f.category=? ';
  1014. $values[] = $id;
  1015. break;
  1016. case 'f': //Feed
  1017. $where .= 'e.id_feed=? ';
  1018. $values[] = $id;
  1019. break;
  1020. case 't': //Tag (label)
  1021. $where .= 'et.id_tag=? ';
  1022. $values[] = $id;
  1023. break;
  1024. case 'T': //Any tag (label)
  1025. $where .= '1=1 ';
  1026. break;
  1027. case 'ST': //Starred or tagged (label)
  1028. $where .= 'e.is_favorite=1 OR EXISTS (SELECT et2.id_tag FROM `_entrytag` et2 WHERE et2.id_entry = e.id) ';
  1029. break;
  1030. default:
  1031. throw new FreshRSS_EntriesGetter_Exception('Bad type in Entry->listByType: [' . $type . ']!');
  1032. }
  1033. [$searchValues, $search] = $this->sqlListEntriesWhere('e.', $filters, $state, $order, $firstId, $date_min);
  1034. return [array_merge($values, $searchValues), 'SELECT '
  1035. . ($type === 'T' ? 'DISTINCT ' : '')
  1036. . 'e.id FROM `_entry` e '
  1037. . 'INNER JOIN `_feed` f ON e.id_feed = f.id '
  1038. . ($type === 't' || $type === 'T' ? 'INNER JOIN `_entrytag` et ON et.id_entry = e.id ' : '')
  1039. . 'WHERE ' . $where
  1040. . $search
  1041. . 'ORDER BY e.id ' . $order
  1042. . ($limit > 0 ? ' LIMIT ' . $limit : '') // http://explainextended.com/2009/10/23/mysql-order-by-limit-performance-late-row-lookups/
  1043. . ($offset > 0 ? ' OFFSET ' . $offset : '')
  1044. ];
  1045. }
  1046. /**
  1047. * @phpstan-param 'a'|'A'|'s'|'S'|'i'|'c'|'f'|'t'|'T'|'ST' $type
  1048. * @param 'ASC'|'DESC' $order
  1049. * @param int $id category/feed/tag ID
  1050. * @return PDOStatement|false
  1051. * @throws FreshRSS_EntriesGetter_Exception
  1052. */
  1053. private function listWhereRaw(string $type = 'a', int $id = 0, int $state = FreshRSS_Entry::STATE_ALL,
  1054. string $order = 'DESC', int $limit = 1, int $offset = 0, string $firstId = '', ?FreshRSS_BooleanSearch $filters = null,
  1055. int $date_min = 0) {
  1056. [$values, $sql] = $this->sqlListWhere($type, $id, $state, $order, $limit, $offset, $firstId, $filters, $date_min);
  1057. if ($order !== 'DESC' && $order !== 'ASC') {
  1058. $order = 'DESC';
  1059. }
  1060. $content = static::isCompressed() ? 'UNCOMPRESS(e0.content_bin) AS content' : 'e0.content';
  1061. $hash = static::sqlHexEncode('e0.hash');
  1062. $sql = <<<SQL
  1063. SELECT e0.id, e0.guid, e0.title, e0.author, {$content}, e0.link, e0.date, {$hash} AS hash, e0.is_read, e0.is_favorite, e0.id_feed, e0.tags, e0.attributes
  1064. FROM `_entry` e0
  1065. INNER JOIN ({$sql}) e2 ON e2.id=e0.id
  1066. ORDER BY e0.id {$order}
  1067. SQL;
  1068. $stm = $this->pdo->prepare($sql);
  1069. if ($stm !== false && $stm->execute($values)) {
  1070. return $stm;
  1071. } else {
  1072. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  1073. if ($this->autoUpdateDb($info)) {
  1074. return $this->listWhereRaw($type, $id, $state, $order, $limit, $offset, $firstId, $filters, $date_min);
  1075. }
  1076. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  1077. return false;
  1078. }
  1079. }
  1080. /**
  1081. * @phpstan-param 'a'|'A'|'s'|'S'|'i'|'c'|'f'|'t'|'T'|'ST' $type
  1082. * @param int $id category/feed/tag ID
  1083. * @param 'ASC'|'DESC' $order
  1084. * @return Traversable<FreshRSS_Entry>
  1085. * @throws FreshRSS_EntriesGetter_Exception
  1086. */
  1087. public function listWhere(string $type = 'a', int $id = 0, int $state = FreshRSS_Entry::STATE_ALL,
  1088. string $order = 'DESC', int $limit = 1, int $offset = 0, string $firstId = '',
  1089. ?FreshRSS_BooleanSearch $filters = null, int $date_min = 0): Traversable {
  1090. $stm = $this->listWhereRaw($type, $id, $state, $order, $limit, $offset, $firstId, $filters, $date_min);
  1091. if ($stm) {
  1092. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  1093. if (is_array($row)) {
  1094. /** @var array{'id':string,'id_feed':int,'guid':string,'title':string,'author':string,'content':string,'link':string,'date':int,
  1095. * 'hash':string,'is_read':int,'is_favorite':int,'tags':string,'attributes'?:?string} $row */
  1096. yield FreshRSS_Entry::fromArray($row);
  1097. }
  1098. }
  1099. }
  1100. }
  1101. /**
  1102. * @param array<numeric-string> $ids
  1103. * @param 'ASC'|'DESC' $order
  1104. * @return Traversable<FreshRSS_Entry>
  1105. */
  1106. public function listByIds(array $ids, string $order = 'DESC'): Traversable {
  1107. if (count($ids) < 1) {
  1108. return;
  1109. }
  1110. if (count($ids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  1111. // Split a query with too many variables parameters
  1112. $idsChunks = array_chunk($ids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  1113. foreach ($idsChunks as $idsChunk) {
  1114. foreach ($this->listByIds($idsChunk, $order) as $entry) {
  1115. yield $entry;
  1116. }
  1117. }
  1118. return;
  1119. }
  1120. if ($order !== 'DESC' && $order !== 'ASC') {
  1121. $order = 'DESC';
  1122. }
  1123. $content = static::isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content';
  1124. $hash = static::sqlHexEncode('hash');
  1125. $repeats = str_repeat('?,', count($ids) - 1) . '?';
  1126. $sql = <<<SQL
  1127. SELECT id, guid, title, author, link, date, {$hash} AS hash, is_read, is_favorite, id_feed, tags, attributes, {$content}
  1128. FROM `_entry`
  1129. WHERE id IN ({$repeats})
  1130. ORDER BY id {$order}
  1131. SQL;
  1132. $stm = $this->pdo->prepare($sql);
  1133. if ($stm === false || !$stm->execute($ids)) {
  1134. return;
  1135. }
  1136. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  1137. if (is_array($row)) {
  1138. /** @var array{'id':string,'id_feed':int,'guid':string,'title':string,'author':string,'content':string,'link':string,'date':int,
  1139. * 'hash':string,'is_read':int,'is_favorite':int,'tags':string,'attributes':?string} $row */
  1140. yield FreshRSS_Entry::fromArray($row);
  1141. }
  1142. }
  1143. }
  1144. /**
  1145. * @phpstan-param 'a'|'A'|'s'|'S'|'c'|'f'|'t'|'T'|'ST' $type
  1146. * @param int $id category/feed/tag ID
  1147. * @param 'ASC'|'DESC' $order
  1148. * @return array<numeric-string>|null
  1149. * @throws FreshRSS_EntriesGetter_Exception
  1150. */
  1151. public function listIdsWhere(string $type = 'a', int $id = 0, int $state = FreshRSS_Entry::STATE_ALL,
  1152. string $order = 'DESC', int $limit = 1, int $offset = 0, string $firstId = '', ?FreshRSS_BooleanSearch $filters = null): ?array {
  1153. [$values, $sql] = $this->sqlListWhere($type, $id, $state, $order, $limit, $offset, $firstId, $filters);
  1154. $stm = $this->pdo->prepare($sql);
  1155. if ($stm !== false && $stm->execute($values) && ($res = $stm->fetchAll(PDO::FETCH_COLUMN, 0)) !== false) {
  1156. /** @var array<numeric-string> $res */
  1157. return $res;
  1158. }
  1159. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  1160. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  1161. return null;
  1162. }
  1163. /**
  1164. * @param array<string> $guids
  1165. * @return array<string>|false
  1166. */
  1167. public function listHashForFeedGuids(int $id_feed, array $guids) {
  1168. $result = [];
  1169. if (count($guids) < 1) {
  1170. return $result;
  1171. } elseif (count($guids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  1172. // Split a query with too many variables parameters
  1173. $guidsChunks = array_chunk($guids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  1174. foreach ($guidsChunks as $guidsChunk) {
  1175. $result += $this->listHashForFeedGuids($id_feed, $guidsChunk);
  1176. }
  1177. return $result;
  1178. }
  1179. $guids = array_unique($guids);
  1180. $sql = 'SELECT guid, ' . static::sqlHexEncode('hash') .
  1181. ' AS hex_hash FROM `_entry` WHERE id_feed=? AND guid IN (' . str_repeat('?,', count($guids) - 1) . '?)';
  1182. $stm = $this->pdo->prepare($sql);
  1183. $values = [$id_feed];
  1184. $values = array_merge($values, $guids);
  1185. if ($stm !== false && $stm->execute($values)) {
  1186. $rows = $stm->fetchAll(PDO::FETCH_ASSOC);
  1187. foreach ($rows as $row) {
  1188. $result[$row['guid']] = $row['hex_hash'];
  1189. }
  1190. return $result;
  1191. } else {
  1192. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  1193. if ($this->autoUpdateDb($info)) {
  1194. return $this->listHashForFeedGuids($id_feed, $guids);
  1195. }
  1196. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info)
  1197. . ' while querying feed ' . $id_feed);
  1198. return false;
  1199. }
  1200. }
  1201. /**
  1202. * @param array<string> $guids
  1203. * @return int|false The number of affected entries, or false if error
  1204. */
  1205. public function updateLastSeen(int $id_feed, array $guids, int $mtime = 0) {
  1206. if (count($guids) < 1) {
  1207. return 0;
  1208. } elseif (count($guids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  1209. // Split a query with too many variables parameters
  1210. $affected = 0;
  1211. $guidsChunks = array_chunk($guids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  1212. foreach ($guidsChunks as $guidsChunk) {
  1213. $affected += ($this->updateLastSeen($id_feed, $guidsChunk, $mtime) ?: 0);
  1214. }
  1215. return $affected;
  1216. }
  1217. $sql = 'UPDATE `_entry` SET `lastSeen`=? WHERE id_feed=? AND guid IN (' . str_repeat('?,', count($guids) - 1) . '?)';
  1218. $stm = $this->pdo->prepare($sql);
  1219. if ($mtime <= 0) {
  1220. $mtime = time();
  1221. }
  1222. $values = [$mtime, $id_feed];
  1223. $values = array_merge($values, $guids);
  1224. if ($stm !== false && $stm->execute($values)) {
  1225. return $stm->rowCount();
  1226. } else {
  1227. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  1228. if ($this->autoUpdateDb($info)) {
  1229. return $this->updateLastSeen($id_feed, $guids);
  1230. }
  1231. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info)
  1232. . ' while updating feed ' . $id_feed);
  1233. return false;
  1234. }
  1235. }
  1236. /**
  1237. * Update (touch) the last seen attribute of the latest entries of a given feed.
  1238. * Useful when a feed is unchanged / cached.
  1239. * To be performed just before {@see FreshRSS_FeedDAO::updateLastUpdate()}
  1240. * @return int|false The number of affected entries, or false in case of error
  1241. */
  1242. public function updateLastSeenUnchanged(int $id_feed, int $mtime = 0) {
  1243. $sql = <<<'SQL'
  1244. UPDATE `_entry` SET `lastSeen` = :mtime
  1245. WHERE id_feed = :id_feed1 AND `lastSeen` = (
  1246. SELECT `lastUpdate` FROM `_feed` f
  1247. WHERE f.id = :id_feed2
  1248. )
  1249. SQL;
  1250. $stm = $this->pdo->prepare($sql);
  1251. if ($mtime <= 0) {
  1252. $mtime = time();
  1253. }
  1254. if ($stm !== false &&
  1255. $stm->bindValue(':mtime', $mtime, PDO::PARAM_INT) &&
  1256. $stm->bindValue(':id_feed1', $id_feed, PDO::PARAM_INT) &&
  1257. $stm->bindValue(':id_feed2', $id_feed, PDO::PARAM_INT) &&
  1258. $stm->execute()) {
  1259. return $stm->rowCount();
  1260. } else {
  1261. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  1262. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info) . ' while updating feed ' . $id_feed);
  1263. return false;
  1264. }
  1265. }
  1266. /** @return array<string,int> */
  1267. public function countUnreadRead(): array {
  1268. $sql = <<<'SQL'
  1269. SELECT COUNT(e.id) AS count FROM `_entry` e
  1270. INNER JOIN `_feed` f ON e.id_feed=f.id
  1271. WHERE f.priority > 0
  1272. UNION
  1273. SELECT COUNT(e.id) AS count FROM `_entry` e
  1274. INNER JOIN `_feed` f ON e.id_feed=f.id
  1275. WHERE f.priority > 0 AND e.is_read=0
  1276. SQL;
  1277. $res = $this->fetchColumn($sql, 0);
  1278. if ($res === null) {
  1279. return ['all' => -1, 'unread' => -1, 'read' => -1];
  1280. }
  1281. rsort($res);
  1282. $all = (int)($res[0] ?? 0);
  1283. $unread = (int)($res[1] ?? 0);
  1284. return ['all' => $all, 'unread' => $unread, 'read' => $all - $unread];
  1285. }
  1286. public function count(?int $minPriority = null): int {
  1287. $sql = 'SELECT COUNT(e.id) AS count FROM `_entry` e';
  1288. $values = [];
  1289. if ($minPriority !== null) {
  1290. $sql .= ' INNER JOIN `_feed` f ON e.id_feed=f.id';
  1291. $sql .= ' WHERE f.priority > :priority';
  1292. $values[':priority'] = $minPriority;
  1293. }
  1294. $res = $this->fetchColumn($sql, 0, $values);
  1295. return isset($res[0]) ? (int)($res[0]) : -1;
  1296. }
  1297. public function countNotRead(?int $minPriority = null): int {
  1298. $sql = 'SELECT COUNT(e.id) AS count FROM `_entry` e';
  1299. if ($minPriority !== null) {
  1300. $sql .= ' INNER JOIN `_feed` f ON e.id_feed=f.id';
  1301. }
  1302. $sql .= ' WHERE e.is_read=0';
  1303. $values = [];
  1304. if ($minPriority !== null) {
  1305. $sql .= ' AND f.priority > :priority';
  1306. $values[':priority'] = $minPriority;
  1307. }
  1308. $res = $this->fetchColumn($sql, 0, $values);
  1309. return isset($res[0]) ? (int)($res[0]) : -1;
  1310. }
  1311. /** @return array{'all':int,'read':int,'unread':int} */
  1312. public function countUnreadReadFavorites(): array {
  1313. $sql = <<<'SQL'
  1314. SELECT c FROM (
  1315. SELECT COUNT(e1.id) AS c, 1 AS o
  1316. FROM `_entry` AS e1
  1317. JOIN `_feed` AS f1 ON e1.id_feed = f1.id
  1318. WHERE e1.is_favorite = 1
  1319. AND f1.priority >= :priority1
  1320. UNION
  1321. SELECT COUNT(e2.id) AS c, 2 AS o
  1322. FROM `_entry` AS e2
  1323. JOIN `_feed` AS f2 ON e2.id_feed = f2.id
  1324. WHERE e2.is_favorite = 1
  1325. AND e2.is_read = 0 AND f2.priority >= :priority2
  1326. ) u
  1327. ORDER BY o
  1328. SQL;
  1329. //Binding a value more than once is not standard and does not work with native prepared statements (e.g. MySQL) https://bugs.php.net/bug.php?id=40417
  1330. $res = $this->fetchColumn($sql, 0, [
  1331. ':priority1' => FreshRSS_Feed::PRIORITY_CATEGORY,
  1332. ':priority2' => FreshRSS_Feed::PRIORITY_CATEGORY,
  1333. ]);
  1334. if ($res === null) {
  1335. return ['all' => -1, 'unread' => -1, 'read' => -1];
  1336. }
  1337. rsort($res);
  1338. $all = (int)($res[0] ?? 0);
  1339. $unread = (int)($res[1] ?? 0);
  1340. return ['all' => $all, 'unread' => $unread, 'read' => $all - $unread];
  1341. }
  1342. }