EntryDAO.php 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425
  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. */
  271. public function markFavorite($ids, bool $is_favorite = true): int|false {
  272. if (!is_array($ids)) {
  273. $ids = [$ids];
  274. }
  275. if (count($ids) < 1) {
  276. return 0;
  277. }
  278. FreshRSS_UserDAO::touch();
  279. if (count($ids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  280. // Split a query with too many variables parameters
  281. $affected = 0;
  282. $idsChunks = array_chunk($ids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  283. foreach ($idsChunks as $idsChunk) {
  284. $affected += ($this->markFavorite($idsChunk, $is_favorite) ?: 0);
  285. }
  286. return $affected;
  287. }
  288. $sql = 'UPDATE `_entry` '
  289. . 'SET is_favorite=? '
  290. . 'WHERE id IN (' . str_repeat('?,', count($ids) - 1) . '?)';
  291. $values = [$is_favorite ? 1 : 0];
  292. $values = array_merge($values, $ids);
  293. $stm = $this->pdo->prepare($sql);
  294. if ($stm !== false && $stm->execute($values)) {
  295. return $stm->rowCount();
  296. } else {
  297. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  298. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  299. return false;
  300. }
  301. }
  302. /**
  303. * Update the unread article cache held on every feed details.
  304. * Depending on the parameters, it updates the cache on one feed, on all
  305. * feeds from one category or on all feeds.
  306. */
  307. protected function updateCacheUnreads(?int $catId = null, ?int $feedId = null): bool {
  308. // Help MySQL/MariaDB's optimizer with the query plan:
  309. $useIndex = $this->pdo->dbType() === 'mysql' ? 'USE INDEX (entry_feed_read_index)' : '';
  310. $sql = <<<SQL
  311. UPDATE `_feed`
  312. SET `cache_nbUnreads`=(
  313. SELECT COUNT(*) AS nbUnreads FROM `_entry` e {$useIndex}
  314. WHERE e.id_feed=`_feed`.id AND e.is_read=0)
  315. SQL;
  316. $hasWhere = false;
  317. $values = [];
  318. if ($feedId != null) {
  319. $sql .= ' WHERE';
  320. $hasWhere = true;
  321. $sql .= ' id=?';
  322. $values[] = $feedId;
  323. }
  324. if ($catId != null) {
  325. $sql .= $hasWhere ? ' AND' : ' WHERE';
  326. $hasWhere = true;
  327. $sql .= ' category=?';
  328. $values[] = $catId;
  329. }
  330. $stm = $this->pdo->prepare($sql);
  331. if ($stm !== false && $stm->execute($values)) {
  332. return true;
  333. } else {
  334. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  335. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  336. return false;
  337. }
  338. }
  339. /**
  340. * Toggle the read marker on one or more article.
  341. * Then the cache is updated.
  342. *
  343. * @param numeric-string|array<numeric-string> $ids
  344. * @return int|false affected rows
  345. */
  346. public function markRead(array|string $ids, bool $is_read = true): int|false {
  347. if (is_array($ids)) { //Many IDs at once
  348. if (count($ids) < 6) { //Speed heuristics
  349. $affected = 0;
  350. foreach ($ids as $id) {
  351. $affected += ($this->markRead($id, $is_read) ?: 0);
  352. }
  353. return $affected;
  354. } elseif (count($ids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  355. // Split a query with too many variables parameters
  356. $affected = 0;
  357. $idsChunks = array_chunk($ids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  358. foreach ($idsChunks as $idsChunk) {
  359. $affected += ($this->markRead($idsChunk, $is_read) ?: 0);
  360. }
  361. return $affected;
  362. }
  363. FreshRSS_UserDAO::touch();
  364. $sql = 'UPDATE `_entry` '
  365. . 'SET is_read=? '
  366. . 'WHERE id IN (' . str_repeat('?,', count($ids) - 1) . '?)';
  367. $values = [$is_read ? 1 : 0];
  368. $values = array_merge($values, $ids);
  369. $stm = $this->pdo->prepare($sql);
  370. if (!($stm && $stm->execute($values))) {
  371. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  372. Minz_Log::error('SQL error ' . __METHOD__ . ' A ' . json_encode($info));
  373. return false;
  374. }
  375. $affected = $stm->rowCount();
  376. if (($affected > 0) && (!$this->updateCacheUnreads(null, null))) {
  377. return false;
  378. }
  379. return $affected;
  380. } else {
  381. FreshRSS_UserDAO::touch();
  382. $sql = 'UPDATE `_entry` e INNER JOIN `_feed` f ON e.id_feed=f.id '
  383. . 'SET e.is_read=?,'
  384. . 'f.`cache_nbUnreads`=f.`cache_nbUnreads`' . ($is_read ? '-' : '+') . '1 '
  385. . 'WHERE e.id=? AND e.is_read=?';
  386. $values = [$is_read ? 1 : 0, $ids, $is_read ? 0 : 1];
  387. $stm = $this->pdo->prepare($sql);
  388. if ($stm !== false && $stm->execute($values)) {
  389. return $stm->rowCount();
  390. } else {
  391. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  392. Minz_Log::error('SQL error ' . __METHOD__ . ' B ' . json_encode($info));
  393. return false;
  394. }
  395. }
  396. }
  397. /**
  398. * Mark all entries as read depending on parameters.
  399. * If $onlyFavorites is true, it is used when the user mark as read in
  400. * the favorite pseudo-category.
  401. * If $priorityMin is greater than 0, it is used when the user mark as
  402. * read in the main feed pseudo-category.
  403. * Then the cache is updated.
  404. *
  405. * If $idMax equals 0, a deprecated debug message is logged
  406. *
  407. * @param numeric-string $idMax fail safe article ID
  408. * @return int|false affected rows
  409. */
  410. public function markReadEntries(string $idMax = '0', bool $onlyFavorites = false, ?int $priorityMin = null, ?int $priorityMax = null,
  411. ?FreshRSS_BooleanSearch $filters = null, int $state = 0, bool $is_read = true) {
  412. FreshRSS_UserDAO::touch();
  413. if ($idMax == '0') {
  414. $idMax = time() . '000000';
  415. Minz_Log::debug('Calling markReadEntries(0) is deprecated!');
  416. }
  417. $sql = 'UPDATE `_entry` SET is_read = ? WHERE is_read <> ? AND id <= ?';
  418. $values = [$is_read ? 1 : 0, $is_read ? 1 : 0, $idMax];
  419. if ($onlyFavorites) {
  420. $sql .= ' AND is_favorite=1';
  421. }
  422. if ($priorityMin !== null || $priorityMax !== null) {
  423. $sql .= ' AND id_feed IN (SELECT f.id FROM `_feed` f WHERE 1=1';
  424. if ($priorityMin !== null) {
  425. $sql .= ' AND f.priority >= ?';
  426. $values[] = $priorityMin;
  427. }
  428. if ($priorityMax !== null) {
  429. $sql .= ' AND f.priority < ?';
  430. $values[] = $priorityMax;
  431. }
  432. $sql .= ')';
  433. }
  434. [$searchValues, $search] = $this->sqlListEntriesWhere('', $filters, $state);
  435. $stm = $this->pdo->prepare($sql . $search);
  436. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  437. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  438. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  439. return false;
  440. }
  441. $affected = $stm->rowCount();
  442. if (($affected > 0) && (!$this->updateCacheUnreads(null, null))) {
  443. return false;
  444. }
  445. return $affected;
  446. }
  447. /**
  448. * Mark all the articles in a category as read.
  449. * There is a fail safe to prevent to mark as read articles that are
  450. * loaded during the mark as read action. Then the cache is updated.
  451. *
  452. * If $idMax equals 0, a deprecated debug message is logged
  453. *
  454. * @param int $id category ID
  455. * @param numeric-string $idMax fail safe article ID
  456. * @return int|false affected rows
  457. */
  458. public function markReadCat(int $id, string $idMax = '0', ?FreshRSS_BooleanSearch $filters = null, int $state = 0, bool $is_read = true): int|false {
  459. FreshRSS_UserDAO::touch();
  460. if ($idMax == '0') {
  461. $idMax = time() . '000000';
  462. Minz_Log::debug('Calling markReadCat(0) is deprecated!');
  463. }
  464. $sql = <<<'SQL'
  465. UPDATE `_entry`
  466. SET is_read = ?
  467. WHERE is_read <> ? AND id <= ?
  468. AND id_feed IN (SELECT f.id FROM `_feed` f WHERE f.category=?)
  469. SQL;
  470. $values = [$is_read ? 1 : 0, $is_read ? 1 : 0, $idMax, $id];
  471. [$searchValues, $search] = $this->sqlListEntriesWhere('', $filters, $state);
  472. $stm = $this->pdo->prepare($sql . $search);
  473. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  474. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  475. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  476. return false;
  477. }
  478. $affected = $stm->rowCount();
  479. if (($affected > 0) && (!$this->updateCacheUnreads($id, null))) {
  480. return false;
  481. }
  482. return $affected;
  483. }
  484. /**
  485. * Mark all the articles in a feed as read.
  486. * There is a fail safe to prevent to mark as read articles that are
  487. * loaded during the mark as read action. Then the cache is updated.
  488. *
  489. * If $idMax equals 0, a deprecated debug message is logged
  490. *
  491. * @param int $id_feed feed ID
  492. * @param numeric-string $idMax fail safe article ID
  493. * @return int|false affected rows
  494. */
  495. public function markReadFeed(int $id_feed, string $idMax = '0', ?FreshRSS_BooleanSearch $filters = null, int $state = 0, bool $is_read = true): int|false {
  496. FreshRSS_UserDAO::touch();
  497. if ($idMax == '0') {
  498. $idMax = time() . '000000';
  499. Minz_Log::debug('Calling markReadFeed(0) is deprecated!');
  500. }
  501. $hadTransaction = $this->pdo->inTransaction();
  502. if (!$hadTransaction) {
  503. $this->pdo->beginTransaction();
  504. }
  505. $sql = 'UPDATE `_entry` '
  506. . 'SET is_read=? '
  507. . 'WHERE id_feed=? AND is_read <> ? AND id <= ?';
  508. $values = [$is_read ? 1 : 0, $id_feed, $is_read ? 1 : 0, $idMax];
  509. [$searchValues, $search] = $this->sqlListEntriesWhere('', $filters, $state);
  510. $stm = $this->pdo->prepare($sql . $search);
  511. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  512. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  513. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info) . ' with SQL: ' . $sql . $search);
  514. $this->pdo->rollBack();
  515. return false;
  516. }
  517. $affected = $stm->rowCount();
  518. if ($affected > 0) {
  519. $sql = 'UPDATE `_feed` '
  520. . 'SET `cache_nbUnreads`=`cache_nbUnreads`-' . $affected
  521. . ' WHERE id=:id';
  522. $stm = $this->pdo->prepare($sql);
  523. if (!($stm !== false &&
  524. $stm->bindParam(':id', $id_feed, PDO::PARAM_INT) &&
  525. $stm->execute())) {
  526. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  527. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  528. $this->pdo->rollBack();
  529. return false;
  530. }
  531. }
  532. if (!$hadTransaction) {
  533. $this->pdo->commit();
  534. }
  535. return $affected;
  536. }
  537. /**
  538. * Mark all the articles in a tag as read.
  539. * @param int $id tag ID, or empty for targeting any tag
  540. * @param numeric-string $idMax max article ID
  541. * @return int|false affected rows
  542. */
  543. public function markReadTag(int $id = 0, string $idMax = '0', ?FreshRSS_BooleanSearch $filters = null,
  544. int $state = 0, bool $is_read = true) {
  545. FreshRSS_UserDAO::touch();
  546. if ($idMax == '0') {
  547. $idMax = time() . '000000';
  548. Minz_Log::debug('Calling markReadTag(0) is deprecated!');
  549. }
  550. $sql = 'UPDATE `_entry` e INNER JOIN `_entrytag` et ON et.id_entry = e.id '
  551. . 'SET e.is_read = ? '
  552. . 'WHERE '
  553. . ($id == 0 ? '' : 'et.id_tag = ? AND ')
  554. . 'e.is_read <> ? AND e.id <= ?';
  555. $values = [$is_read ? 1 : 0];
  556. if ($id != 0) {
  557. $values[] = $id;
  558. }
  559. $values[] = $is_read ? 1 : 0;
  560. $values[] = $idMax;
  561. [$searchValues, $search] = $this->sqlListEntriesWhere('e.', $filters, $state);
  562. $stm = $this->pdo->prepare($sql . $search);
  563. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  564. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  565. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  566. return false;
  567. }
  568. $affected = $stm->rowCount();
  569. if (($affected > 0) && (!$this->updateCacheUnreads(null, null))) {
  570. return false;
  571. }
  572. return $affected;
  573. }
  574. /**
  575. * Remember to call updateCachedValues($id_feed) or updateCachedValues() just after.
  576. * @param array<string,bool|int|string> $options
  577. */
  578. public function cleanOldEntries(int $id_feed, array $options = []): int|false {
  579. $sql = 'DELETE FROM `_entry` WHERE id_feed = :id_feed1'; //No alias for MySQL / MariaDB
  580. $params = [];
  581. $params[':id_feed1'] = $id_feed;
  582. //==Exclusions==
  583. if (!empty($options['keep_favourites'])) {
  584. $sql .= ' AND is_favorite = 0';
  585. }
  586. if (!empty($options['keep_unreads'])) {
  587. $sql .= ' AND is_read = 1';
  588. }
  589. if (!empty($options['keep_labels'])) {
  590. $sql .= ' AND NOT EXISTS (SELECT 1 FROM `_entrytag` WHERE id_entry = id)';
  591. }
  592. if (!empty($options['keep_min']) && $options['keep_min'] > 0) {
  593. //Double SELECT for MySQL workaround ERROR 1093 (HY000)
  594. $sql .= ' AND `lastSeen` < (SELECT `lastSeen`'
  595. . ' FROM (SELECT e2.`lastSeen` FROM `_entry` e2 WHERE e2.id_feed = :id_feed2'
  596. . ' ORDER BY e2.`lastSeen` DESC LIMIT 1 OFFSET :keep_min) last_seen2)';
  597. $params[':id_feed2'] = $id_feed;
  598. $params[':keep_min'] = (int)$options['keep_min'];
  599. }
  600. //Keep at least the articles seen at the last refresh
  601. $sql .= ' AND `lastSeen` < (SELECT maxlastseen'
  602. . ' FROM (SELECT MAX(e3.`lastSeen`) AS maxlastseen FROM `_entry` e3 WHERE e3.id_feed = :id_feed3) last_seen3)';
  603. $params[':id_feed3'] = $id_feed;
  604. //==Inclusions==
  605. $sql .= ' AND (1=0';
  606. if (!empty($options['keep_period']) && is_string($options['keep_period'])) {
  607. $sql .= ' OR `lastSeen` < :max_last_seen';
  608. $now = new DateTime('now');
  609. $now->sub(new DateInterval($options['keep_period']));
  610. $params[':max_last_seen'] = $now->format('U');
  611. }
  612. if (!empty($options['keep_max']) && $options['keep_max'] > 0) {
  613. $sql .= ' OR `lastSeen` <= (SELECT `lastSeen`'
  614. . ' FROM (SELECT e4.`lastSeen` FROM `_entry` e4 WHERE e4.id_feed = :id_feed4'
  615. . ' ORDER BY e4.`lastSeen` DESC LIMIT 1 OFFSET :keep_max) last_seen4)';
  616. $params[':id_feed4'] = $id_feed;
  617. $params[':keep_max'] = (int)$options['keep_max'];
  618. }
  619. $sql .= ')';
  620. $stm = $this->pdo->prepare($sql);
  621. if ($stm !== false && $stm->execute($params)) {
  622. return $stm->rowCount();
  623. } else {
  624. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  625. if ($this->autoUpdateDb($info)) {
  626. return $this->cleanOldEntries($id_feed, $options);
  627. }
  628. Minz_Log::error(__method__ . ' error:' . json_encode($info));
  629. return false;
  630. }
  631. }
  632. /** @return Traversable<array{'id':string,'guid':string,'title':string,'author':string,'content':string,'link':string,'date':int,'lastSeen':int,
  633. * 'hash':string,'is_read':bool,'is_favorite':bool,'id_feed':int,'tags':string,'attributes':?string}> */
  634. public function selectAll(?int $limit = null): Traversable {
  635. $content = static::isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content';
  636. $hash = static::sqlHexEncode('hash');
  637. $sql = <<<SQL
  638. SELECT id, guid, title, author, {$content}, link, date, `lastSeen`, {$hash} AS hash, is_read, is_favorite, id_feed, tags, attributes
  639. FROM `_entry`
  640. SQL;
  641. if (is_int($limit) && $limit >= 0) {
  642. $sql .= ' ORDER BY id DESC LIMIT ' . $limit;
  643. }
  644. $stm = $this->pdo->query($sql);
  645. if ($stm != false) {
  646. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  647. /** @var array{'id':string,'guid':string,'title':string,'author':string,'content':string,'link':string,'date':int,'lastSeen':int,
  648. * 'hash':string,'is_read':bool,'is_favorite':bool,'id_feed':int,'tags':string,'attributes':?string} $row */
  649. yield $row;
  650. }
  651. } else {
  652. $info = $this->pdo->errorInfo();
  653. if ($this->autoUpdateDb($info)) {
  654. yield from $this->selectAll();
  655. } else {
  656. Minz_Log::error(__method__ . ' error: ' . json_encode($info));
  657. }
  658. }
  659. }
  660. public function searchByGuid(int $id_feed, string $guid): ?FreshRSS_Entry {
  661. $content = static::isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content';
  662. $hash = static::sqlHexEncode('hash');
  663. $sql = <<<SQL
  664. SELECT id, guid, title, author, link, date, is_read, is_favorite, {$hash} AS hash, id_feed, tags, attributes, {$content}
  665. FROM `_entry` WHERE id_feed=:id_feed AND guid=:guid
  666. SQL;
  667. $res = $this->fetchAssoc($sql, [':id_feed' => $id_feed, ':guid' => $guid]);
  668. /** @var array<array{'id':string,'id_feed':int,'guid':string,'title':string,'author':string,'content':string,'link':string,'date':int,
  669. * 'is_read':int,'is_favorite':int,'tags':string,'attributes':?string}> $res */
  670. return isset($res[0]) ? FreshRSS_Entry::fromArray($res[0]) : null;
  671. }
  672. public function searchById(string $id): ?FreshRSS_Entry {
  673. $content = static::isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content';
  674. $hash = static::sqlHexEncode('hash');
  675. $sql = <<<SQL
  676. SELECT id, guid, title, author, link, date, is_read, is_favorite, {$hash} AS hash, id_feed, tags, attributes, {$content}
  677. FROM `_entry` WHERE id=:id
  678. SQL;
  679. $res = $this->fetchAssoc($sql, [':id' => $id]);
  680. /** @var array<array{'id':string,'id_feed':int,'guid':string,'title':string,'author':string,'content':string,'link':string,'date':int,
  681. * 'is_read':int,'is_favorite':int,'tags':string,'attributes':?string}> $res */
  682. return isset($res[0]) ? FreshRSS_Entry::fromArray($res[0]) : null;
  683. }
  684. public function searchIdByGuid(int $id_feed, string $guid): ?string {
  685. $sql = 'SELECT id FROM `_entry` WHERE id_feed=:id_feed AND guid=:guid';
  686. $res = $this->fetchColumn($sql, 0, [':id_feed' => $id_feed, ':guid' => $guid]);
  687. return empty($res[0]) ? null : (string)($res[0]);
  688. }
  689. /** @return array{0:array<int|string>,1:string} */
  690. public static function sqlBooleanSearch(string $alias, FreshRSS_BooleanSearch $filters, int $level = 0): array {
  691. $search = '';
  692. $values = [];
  693. $isOpen = false;
  694. foreach ($filters->searches() as $filter) {
  695. if ($filter == null) {
  696. continue;
  697. }
  698. if ($filter instanceof FreshRSS_BooleanSearch) {
  699. // BooleanSearches are combined by AND (default) or OR (special case) operator and are recursive
  700. [$filterValues, $filterSearch] = self::sqlBooleanSearch($alias, $filter, $level + 1);
  701. $filterSearch = trim($filterSearch);
  702. if ($filterSearch !== '') {
  703. if ($search !== '') {
  704. $search .= $filter->operator();
  705. } elseif (in_array($filter->operator(), ['AND NOT', 'OR NOT'], true)) {
  706. // Special case if we start with a negation (there is already the default AND before)
  707. $search .= ' NOT';
  708. }
  709. $search .= ' (' . $filterSearch . ') ';
  710. $values = array_merge($values, $filterValues);
  711. }
  712. continue;
  713. }
  714. // Searches are combined by OR and are not recursive
  715. $sub_search = '';
  716. if ($filter->getEntryIds() !== null) {
  717. $sub_search .= 'AND ' . $alias . 'id IN (';
  718. foreach ($filter->getEntryIds() as $entry_id) {
  719. $sub_search .= '?,';
  720. $values[] = $entry_id;
  721. }
  722. $sub_search = rtrim($sub_search, ',');
  723. $sub_search .= ') ';
  724. }
  725. if ($filter->getNotEntryIds() !== null) {
  726. $sub_search .= 'AND ' . $alias . 'id NOT IN (';
  727. foreach ($filter->getNotEntryIds() as $entry_id) {
  728. $sub_search .= '?,';
  729. $values[] = $entry_id;
  730. }
  731. $sub_search = rtrim($sub_search, ',');
  732. $sub_search .= ') ';
  733. }
  734. if ($filter->getMinDate() !== null) {
  735. $sub_search .= 'AND ' . $alias . 'id >= ? ';
  736. $values[] = "{$filter->getMinDate()}000000";
  737. }
  738. if ($filter->getMaxDate() !== null) {
  739. $sub_search .= 'AND ' . $alias . 'id <= ? ';
  740. $values[] = "{$filter->getMaxDate()}000000";
  741. }
  742. if ($filter->getMinPubdate() !== null) {
  743. $sub_search .= 'AND ' . $alias . 'date >= ? ';
  744. $values[] = $filter->getMinPubdate();
  745. }
  746. if ($filter->getMaxPubdate() !== null) {
  747. $sub_search .= 'AND ' . $alias . 'date <= ? ';
  748. $values[] = $filter->getMaxPubdate();
  749. }
  750. //Negation of date intervals must be combined by OR
  751. if ($filter->getNotMinDate() !== null || $filter->getNotMaxDate() !== null) {
  752. $sub_search .= 'AND (';
  753. if ($filter->getNotMinDate() !== null) {
  754. $sub_search .= $alias . 'id < ?';
  755. $values[] = "{$filter->getNotMinDate()}000000";
  756. if ($filter->getNotMaxDate()) {
  757. $sub_search .= ' OR ';
  758. }
  759. }
  760. if ($filter->getNotMaxDate() !== null) {
  761. $sub_search .= $alias . 'id > ?';
  762. $values[] = "{$filter->getNotMaxDate()}000000";
  763. }
  764. $sub_search .= ') ';
  765. }
  766. if ($filter->getNotMinPubdate() !== null || $filter->getNotMaxPubdate() !== null) {
  767. $sub_search .= 'AND (';
  768. if ($filter->getNotMinPubdate() !== null) {
  769. $sub_search .= $alias . 'date < ?';
  770. $values[] = $filter->getNotMinPubdate();
  771. if ($filter->getNotMaxPubdate()) {
  772. $sub_search .= ' OR ';
  773. }
  774. }
  775. if ($filter->getNotMaxPubdate() !== null) {
  776. $sub_search .= $alias . 'date > ?';
  777. $values[] = $filter->getNotMaxPubdate();
  778. }
  779. $sub_search .= ') ';
  780. }
  781. if ($filter->getFeedIds() !== null) {
  782. $sub_search .= 'AND ' . $alias . 'id_feed IN (';
  783. foreach ($filter->getFeedIds() as $feed_id) {
  784. $sub_search .= '?,';
  785. $values[] = $feed_id;
  786. }
  787. $sub_search = rtrim($sub_search, ',');
  788. $sub_search .= ') ';
  789. }
  790. if ($filter->getNotFeedIds() !== null) {
  791. $sub_search .= 'AND ' . $alias . 'id_feed NOT IN (';
  792. foreach ($filter->getNotFeedIds() as $feed_id) {
  793. $sub_search .= '?,';
  794. $values[] = $feed_id;
  795. }
  796. $sub_search = rtrim($sub_search, ',');
  797. $sub_search .= ') ';
  798. }
  799. if ($filter->getLabelIds() !== null) {
  800. if ($filter->getLabelIds() === '*') {
  801. $sub_search .= 'AND EXISTS (SELECT et.id_tag FROM `_entrytag` et WHERE et.id_entry = ' . $alias . 'id) ';
  802. } else {
  803. $sub_search .= 'AND ' . $alias . 'id IN (SELECT et.id_entry FROM `_entrytag` et WHERE et.id_tag IN (';
  804. foreach ($filter->getLabelIds() as $label_id) {
  805. $sub_search .= '?,';
  806. $values[] = $label_id;
  807. }
  808. $sub_search = rtrim($sub_search, ',');
  809. $sub_search .= ')) ';
  810. }
  811. }
  812. if ($filter->getNotLabelIds() !== null) {
  813. if ($filter->getNotLabelIds() === '*') {
  814. $sub_search .= 'AND NOT EXISTS (SELECT et.id_tag FROM `_entrytag` et WHERE et.id_entry = ' . $alias . 'id) ';
  815. } else {
  816. $sub_search .= 'AND ' . $alias . 'id NOT IN (SELECT et.id_entry FROM `_entrytag` et WHERE et.id_tag IN (';
  817. foreach ($filter->getNotLabelIds() as $label_id) {
  818. $sub_search .= '?,';
  819. $values[] = $label_id;
  820. }
  821. $sub_search = rtrim($sub_search, ',');
  822. $sub_search .= ')) ';
  823. }
  824. }
  825. if ($filter->getLabelNames() !== null) {
  826. $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 (';
  827. foreach ($filter->getLabelNames() as $label_name) {
  828. $sub_search .= '?,';
  829. $values[] = $label_name;
  830. }
  831. $sub_search = rtrim($sub_search, ',');
  832. $sub_search .= ')) ';
  833. }
  834. if ($filter->getNotLabelNames() !== null) {
  835. $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 (';
  836. foreach ($filter->getNotLabelNames() as $label_name) {
  837. $sub_search .= '?,';
  838. $values[] = $label_name;
  839. }
  840. $sub_search = rtrim($sub_search, ',');
  841. $sub_search .= ')) ';
  842. }
  843. if ($filter->getAuthor() !== null) {
  844. foreach ($filter->getAuthor() as $author) {
  845. $sub_search .= 'AND ' . $alias . 'author LIKE ? ';
  846. $values[] = "%{$author}%";
  847. }
  848. }
  849. if ($filter->getIntitle() !== null) {
  850. foreach ($filter->getIntitle() as $title) {
  851. $sub_search .= 'AND ' . $alias . 'title LIKE ? ';
  852. $values[] = "%{$title}%";
  853. }
  854. }
  855. if ($filter->getTags() !== null) {
  856. foreach ($filter->getTags() as $tag) {
  857. $sub_search .= 'AND ' . static::sqlConcat('TRIM(' . $alias . 'tags) ', " ' #'") . ' LIKE ? ';
  858. $values[] = "%{$tag} #%";
  859. }
  860. }
  861. if ($filter->getInurl() !== null) {
  862. foreach ($filter->getInurl() as $url) {
  863. $sub_search .= 'AND ' . $alias . 'link LIKE ? ';
  864. $values[] = "%{$url}%";
  865. }
  866. }
  867. if ($filter->getNotAuthor() !== null) {
  868. foreach ($filter->getNotAuthor() as $author) {
  869. $sub_search .= 'AND ' . $alias . 'author NOT LIKE ? ';
  870. $values[] = "%{$author}%";
  871. }
  872. }
  873. if ($filter->getNotIntitle() !== null) {
  874. foreach ($filter->getNotIntitle() as $title) {
  875. $sub_search .= 'AND ' . $alias . 'title NOT LIKE ? ';
  876. $values[] = "%{$title}%";
  877. }
  878. }
  879. if ($filter->getNotTags() !== null) {
  880. foreach ($filter->getNotTags() as $tag) {
  881. $sub_search .= 'AND ' . static::sqlConcat('TRIM(' . $alias . 'tags) ', " ' #'") . ' NOT LIKE ? ';
  882. $values[] = "%{$tag} #%";
  883. }
  884. }
  885. if ($filter->getNotInurl() !== null) {
  886. foreach ($filter->getNotInurl() as $url) {
  887. $sub_search .= 'AND ' . $alias . 'link NOT LIKE ? ';
  888. $values[] = "%{$url}%";
  889. }
  890. }
  891. if ($filter->getSearch() !== null) {
  892. foreach ($filter->getSearch() as $search_value) {
  893. if (static::isCompressed()) { // MySQL-only
  894. $sub_search .= 'AND CONCAT(' . $alias . 'title, UNCOMPRESS(' . $alias . 'content_bin)) LIKE ? ';
  895. $values[] = "%{$search_value}%";
  896. } else {
  897. $sub_search .= 'AND (' . $alias . 'title LIKE ? OR ' . $alias . 'content LIKE ?) ';
  898. $values[] = "%{$search_value}%";
  899. $values[] = "%{$search_value}%";
  900. }
  901. }
  902. }
  903. if ($filter->getNotSearch() !== null) {
  904. foreach ($filter->getNotSearch() as $search_value) {
  905. if (static::isCompressed()) { // MySQL-only
  906. $sub_search .= 'AND CONCAT(' . $alias . 'title, UNCOMPRESS(' . $alias . 'content_bin)) NOT LIKE ? ';
  907. $values[] = "%{$search_value}%";
  908. } else {
  909. $sub_search .= 'AND ' . $alias . 'title NOT LIKE ? AND ' . $alias . 'content NOT LIKE ? ';
  910. $values[] = "%{$search_value}%";
  911. $values[] = "%{$search_value}%";
  912. }
  913. }
  914. }
  915. if ($sub_search != '') {
  916. if ($isOpen) {
  917. $search .= ' OR ';
  918. } else {
  919. $isOpen = true;
  920. }
  921. // Remove superfluous leading 'AND '
  922. $search .= '(' . substr($sub_search, 4) . ')';
  923. }
  924. }
  925. return [ $values, $search ];
  926. }
  927. /**
  928. * @param 'ASC'|'DESC' $order
  929. * @return array{0:array<int|string>,1:string}
  930. * @throws FreshRSS_EntriesGetter_Exception
  931. */
  932. protected function sqlListEntriesWhere(string $alias = '', ?FreshRSS_BooleanSearch $filters = null,
  933. int $state = FreshRSS_Entry::STATE_ALL,
  934. string $order = 'DESC', string $firstId = '', int $date_min = 0): array {
  935. $search = ' ';
  936. $values = [];
  937. if ($state & FreshRSS_Entry::STATE_NOT_READ) {
  938. if (!($state & FreshRSS_Entry::STATE_READ)) {
  939. $search .= 'AND ' . $alias . 'is_read=0 ';
  940. }
  941. } elseif ($state & FreshRSS_Entry::STATE_READ) {
  942. $search .= 'AND ' . $alias . 'is_read=1 ';
  943. }
  944. if ($state & FreshRSS_Entry::STATE_FAVORITE) {
  945. if (!($state & FreshRSS_Entry::STATE_NOT_FAVORITE)) {
  946. $search .= 'AND ' . $alias . 'is_favorite=1 ';
  947. }
  948. } elseif ($state & FreshRSS_Entry::STATE_NOT_FAVORITE) {
  949. $search .= 'AND ' . $alias . 'is_favorite=0 ';
  950. }
  951. switch ($order) {
  952. case 'DESC':
  953. case 'ASC':
  954. break;
  955. default:
  956. throw new FreshRSS_EntriesGetter_Exception('Bad order in Entry->listByType: [' . $order . ']!');
  957. }
  958. if ($firstId !== '') {
  959. $search .= 'AND ' . $alias . 'id ' . ($order === 'DESC' ? '<=' : '>=') . ' ? ';
  960. $values[] = $firstId;
  961. }
  962. if ($date_min > 0) {
  963. $search .= 'AND ' . $alias . 'id >= ? ';
  964. $values[] = $date_min . '000000';
  965. }
  966. if ($filters && count($filters->searches()) > 0) {
  967. [$filterValues, $filterSearch] = self::sqlBooleanSearch($alias, $filters);
  968. $filterSearch = trim($filterSearch);
  969. if ($filterSearch !== '') {
  970. $search .= 'AND (' . $filterSearch . ') ';
  971. $values = array_merge($values, $filterValues);
  972. }
  973. }
  974. return [$values, $search];
  975. }
  976. /**
  977. * @phpstan-param 'a'|'A'|'i'|'s'|'S'|'c'|'f'|'t'|'T'|'ST' $type
  978. * @param int $id category/feed/tag ID
  979. * @param 'ASC'|'DESC' $order
  980. * @return array{0:array<int|string>,1:string}
  981. * @throws FreshRSS_EntriesGetter_Exception
  982. */
  983. private function sqlListWhere(string $type = 'a', int $id = 0, int $state = FreshRSS_Entry::STATE_ALL,
  984. string $order = 'DESC', int $limit = 1, int $offset = 0, string $firstId = '', ?FreshRSS_BooleanSearch $filters = null,
  985. int $date_min = 0): array {
  986. if (!$state) {
  987. $state = FreshRSS_Entry::STATE_ALL;
  988. }
  989. $where = '';
  990. $values = [];
  991. switch ($type) {
  992. case 'a': //All PRIORITY_MAIN_STREAM
  993. $where .= 'f.priority >= ' . FreshRSS_Feed::PRIORITY_MAIN_STREAM . ' ';
  994. break;
  995. case 'A': //All except PRIORITY_ARCHIVED
  996. $where .= 'f.priority > ' . FreshRSS_Feed::PRIORITY_ARCHIVED . ' ';
  997. break;
  998. case 'i': //Priority important feeds
  999. $where .= 'f.priority >= ' . FreshRSS_Feed::PRIORITY_IMPORTANT . ' ';
  1000. break;
  1001. case 's': //Starred. Deprecated: use $state instead
  1002. $where .= 'f.priority > ' . FreshRSS_Feed::PRIORITY_ARCHIVED . ' ';
  1003. $where .= 'AND e.is_favorite=1 ';
  1004. break;
  1005. case 'S': //Starred
  1006. $where .= 'e.is_favorite=1 ';
  1007. break;
  1008. case 'c': //Category
  1009. $where .= 'f.priority >= ' . FreshRSS_Feed::PRIORITY_CATEGORY . ' ';
  1010. $where .= 'AND f.category=? ';
  1011. $values[] = $id;
  1012. break;
  1013. case 'f': //Feed
  1014. $where .= 'e.id_feed=? ';
  1015. $values[] = $id;
  1016. break;
  1017. case 't': //Tag (label)
  1018. $where .= 'et.id_tag=? ';
  1019. $values[] = $id;
  1020. break;
  1021. case 'T': //Any tag (label)
  1022. $where .= '1=1 ';
  1023. break;
  1024. case 'ST': //Starred or tagged (label)
  1025. $where .= 'e.is_favorite=1 OR EXISTS (SELECT et2.id_tag FROM `_entrytag` et2 WHERE et2.id_entry = e.id) ';
  1026. break;
  1027. default:
  1028. throw new FreshRSS_EntriesGetter_Exception('Bad type in Entry->listByType: [' . $type . ']!');
  1029. }
  1030. [$searchValues, $search] = $this->sqlListEntriesWhere('e.', $filters, $state, $order, $firstId, $date_min);
  1031. return [array_merge($values, $searchValues), 'SELECT '
  1032. . ($type === 'T' ? 'DISTINCT ' : '')
  1033. . 'e.id FROM `_entry` e '
  1034. . 'INNER JOIN `_feed` f ON e.id_feed = f.id '
  1035. . ($type === 't' || $type === 'T' ? 'INNER JOIN `_entrytag` et ON et.id_entry = e.id ' : '')
  1036. . 'WHERE ' . $where
  1037. . $search
  1038. . 'ORDER BY e.id ' . $order
  1039. . ($limit > 0 ? ' LIMIT ' . $limit : '') // http://explainextended.com/2009/10/23/mysql-order-by-limit-performance-late-row-lookups/
  1040. . ($offset > 0 ? ' OFFSET ' . $offset : '')
  1041. ];
  1042. }
  1043. /**
  1044. * @phpstan-param 'a'|'A'|'s'|'S'|'i'|'c'|'f'|'t'|'T'|'ST' $type
  1045. * @param 'ASC'|'DESC' $order
  1046. * @param int $id category/feed/tag ID
  1047. * @throws FreshRSS_EntriesGetter_Exception
  1048. */
  1049. private function listWhereRaw(string $type = 'a', int $id = 0, int $state = FreshRSS_Entry::STATE_ALL,
  1050. string $order = 'DESC', int $limit = 1, int $offset = 0, string $firstId = '', ?FreshRSS_BooleanSearch $filters = null,
  1051. int $date_min = 0): PDOStatement|false {
  1052. [$values, $sql] = $this->sqlListWhere($type, $id, $state, $order, $limit, $offset, $firstId, $filters, $date_min);
  1053. if ($order !== 'DESC' && $order !== 'ASC') {
  1054. $order = 'DESC';
  1055. }
  1056. $content = static::isCompressed() ? 'UNCOMPRESS(e0.content_bin) AS content' : 'e0.content';
  1057. $hash = static::sqlHexEncode('e0.hash');
  1058. $sql = <<<SQL
  1059. 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
  1060. FROM `_entry` e0
  1061. INNER JOIN ({$sql}) e2 ON e2.id=e0.id
  1062. ORDER BY e0.id {$order}
  1063. SQL;
  1064. $stm = $this->pdo->prepare($sql);
  1065. if ($stm !== false && $stm->execute($values)) {
  1066. return $stm;
  1067. } else {
  1068. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  1069. if ($this->autoUpdateDb($info)) {
  1070. return $this->listWhereRaw($type, $id, $state, $order, $limit, $offset, $firstId, $filters, $date_min);
  1071. }
  1072. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  1073. return false;
  1074. }
  1075. }
  1076. /**
  1077. * @phpstan-param 'a'|'A'|'s'|'S'|'i'|'c'|'f'|'t'|'T'|'ST' $type
  1078. * @param int $id category/feed/tag ID
  1079. * @param 'ASC'|'DESC' $order
  1080. * @return Traversable<FreshRSS_Entry>
  1081. * @throws FreshRSS_EntriesGetter_Exception
  1082. */
  1083. public function listWhere(string $type = 'a', int $id = 0, int $state = FreshRSS_Entry::STATE_ALL,
  1084. string $order = 'DESC', int $limit = 1, int $offset = 0, string $firstId = '',
  1085. ?FreshRSS_BooleanSearch $filters = null, int $date_min = 0): Traversable {
  1086. $stm = $this->listWhereRaw($type, $id, $state, $order, $limit, $offset, $firstId, $filters, $date_min);
  1087. if ($stm) {
  1088. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  1089. if (is_array($row)) {
  1090. /** @var array{'id':string,'id_feed':int,'guid':string,'title':string,'author':string,'content':string,'link':string,'date':int,
  1091. * 'hash':string,'is_read':int,'is_favorite':int,'tags':string,'attributes'?:?string} $row */
  1092. yield FreshRSS_Entry::fromArray($row);
  1093. }
  1094. }
  1095. }
  1096. }
  1097. /**
  1098. * @param array<numeric-string> $ids
  1099. * @param 'ASC'|'DESC' $order
  1100. * @return Traversable<FreshRSS_Entry>
  1101. */
  1102. public function listByIds(array $ids, string $order = 'DESC'): Traversable {
  1103. if (count($ids) < 1) {
  1104. return;
  1105. }
  1106. if (count($ids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  1107. // Split a query with too many variables parameters
  1108. $idsChunks = array_chunk($ids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  1109. foreach ($idsChunks as $idsChunk) {
  1110. foreach ($this->listByIds($idsChunk, $order) as $entry) {
  1111. yield $entry;
  1112. }
  1113. }
  1114. return;
  1115. }
  1116. if ($order !== 'DESC' && $order !== 'ASC') {
  1117. $order = 'DESC';
  1118. }
  1119. $content = static::isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content';
  1120. $hash = static::sqlHexEncode('hash');
  1121. $repeats = str_repeat('?,', count($ids) - 1) . '?';
  1122. $sql = <<<SQL
  1123. SELECT id, guid, title, author, link, date, {$hash} AS hash, is_read, is_favorite, id_feed, tags, attributes, {$content}
  1124. FROM `_entry`
  1125. WHERE id IN ({$repeats})
  1126. ORDER BY id {$order}
  1127. SQL;
  1128. $stm = $this->pdo->prepare($sql);
  1129. if ($stm === false || !$stm->execute($ids)) {
  1130. return;
  1131. }
  1132. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  1133. if (is_array($row)) {
  1134. /** @var array{'id':string,'id_feed':int,'guid':string,'title':string,'author':string,'content':string,'link':string,'date':int,
  1135. * 'hash':string,'is_read':int,'is_favorite':int,'tags':string,'attributes':?string} $row */
  1136. yield FreshRSS_Entry::fromArray($row);
  1137. }
  1138. }
  1139. }
  1140. /**
  1141. * @phpstan-param 'a'|'A'|'s'|'S'|'c'|'f'|'t'|'T'|'ST' $type
  1142. * @param int $id category/feed/tag ID
  1143. * @param 'ASC'|'DESC' $order
  1144. * @return array<numeric-string>|null
  1145. * @throws FreshRSS_EntriesGetter_Exception
  1146. */
  1147. public function listIdsWhere(string $type = 'a', int $id = 0, int $state = FreshRSS_Entry::STATE_ALL,
  1148. string $order = 'DESC', int $limit = 1, int $offset = 0, string $firstId = '', ?FreshRSS_BooleanSearch $filters = null): ?array {
  1149. [$values, $sql] = $this->sqlListWhere($type, $id, $state, $order, $limit, $offset, $firstId, $filters);
  1150. $stm = $this->pdo->prepare($sql);
  1151. if ($stm !== false && $stm->execute($values) && ($res = $stm->fetchAll(PDO::FETCH_COLUMN, 0)) !== false) {
  1152. /** @var array<numeric-string> $res */
  1153. return $res;
  1154. }
  1155. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  1156. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  1157. return null;
  1158. }
  1159. /**
  1160. * @param array<string> $guids
  1161. * @return array<string>|false
  1162. */
  1163. public function listHashForFeedGuids(int $id_feed, array $guids): array|false {
  1164. $result = [];
  1165. if (count($guids) < 1) {
  1166. return $result;
  1167. } elseif (count($guids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  1168. // Split a query with too many variables parameters
  1169. $guidsChunks = array_chunk($guids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  1170. foreach ($guidsChunks as $guidsChunk) {
  1171. $result += $this->listHashForFeedGuids($id_feed, $guidsChunk);
  1172. }
  1173. return $result;
  1174. }
  1175. $guids = array_unique($guids);
  1176. $sql = 'SELECT guid, ' . static::sqlHexEncode('hash') .
  1177. ' AS hex_hash FROM `_entry` WHERE id_feed=? AND guid IN (' . str_repeat('?,', count($guids) - 1) . '?)';
  1178. $stm = $this->pdo->prepare($sql);
  1179. $values = [$id_feed];
  1180. $values = array_merge($values, $guids);
  1181. if ($stm !== false && $stm->execute($values)) {
  1182. $rows = $stm->fetchAll(PDO::FETCH_ASSOC);
  1183. foreach ($rows as $row) {
  1184. $result[$row['guid']] = $row['hex_hash'];
  1185. }
  1186. return $result;
  1187. } else {
  1188. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  1189. if ($this->autoUpdateDb($info)) {
  1190. return $this->listHashForFeedGuids($id_feed, $guids);
  1191. }
  1192. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info)
  1193. . ' while querying feed ' . $id_feed);
  1194. return false;
  1195. }
  1196. }
  1197. /**
  1198. * @param array<string> $guids
  1199. * @return int|false The number of affected entries, or false if error
  1200. */
  1201. public function updateLastSeen(int $id_feed, array $guids, int $mtime = 0): int|false {
  1202. if (count($guids) < 1) {
  1203. return 0;
  1204. } elseif (count($guids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  1205. // Split a query with too many variables parameters
  1206. $affected = 0;
  1207. $guidsChunks = array_chunk($guids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  1208. foreach ($guidsChunks as $guidsChunk) {
  1209. $affected += ($this->updateLastSeen($id_feed, $guidsChunk, $mtime) ?: 0);
  1210. }
  1211. return $affected;
  1212. }
  1213. $sql = 'UPDATE `_entry` SET `lastSeen`=? WHERE id_feed=? AND guid IN (' . str_repeat('?,', count($guids) - 1) . '?)';
  1214. $stm = $this->pdo->prepare($sql);
  1215. if ($mtime <= 0) {
  1216. $mtime = time();
  1217. }
  1218. $values = [$mtime, $id_feed];
  1219. $values = array_merge($values, $guids);
  1220. if ($stm !== false && $stm->execute($values)) {
  1221. return $stm->rowCount();
  1222. } else {
  1223. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  1224. if ($this->autoUpdateDb($info)) {
  1225. return $this->updateLastSeen($id_feed, $guids);
  1226. }
  1227. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info)
  1228. . ' while updating feed ' . $id_feed);
  1229. return false;
  1230. }
  1231. }
  1232. /**
  1233. * Update (touch) the last seen attribute of the latest entries of a given feed.
  1234. * Useful when a feed is unchanged / cached.
  1235. * To be performed just before {@see FreshRSS_FeedDAO::updateLastUpdate()}
  1236. * @return int|false The number of affected entries, or false in case of error
  1237. */
  1238. public function updateLastSeenUnchanged(int $id_feed, int $mtime = 0): int|false {
  1239. $sql = <<<'SQL'
  1240. UPDATE `_entry` SET `lastSeen` = :mtime
  1241. WHERE id_feed = :id_feed1 AND `lastSeen` = (
  1242. SELECT `lastUpdate` FROM `_feed` f
  1243. WHERE f.id = :id_feed2
  1244. )
  1245. SQL;
  1246. $stm = $this->pdo->prepare($sql);
  1247. if ($mtime <= 0) {
  1248. $mtime = time();
  1249. }
  1250. if ($stm !== false &&
  1251. $stm->bindValue(':mtime', $mtime, PDO::PARAM_INT) &&
  1252. $stm->bindValue(':id_feed1', $id_feed, PDO::PARAM_INT) &&
  1253. $stm->bindValue(':id_feed2', $id_feed, PDO::PARAM_INT) &&
  1254. $stm->execute()) {
  1255. return $stm->rowCount();
  1256. } else {
  1257. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  1258. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info) . ' while updating feed ' . $id_feed);
  1259. return false;
  1260. }
  1261. }
  1262. /** @return array<string,int> */
  1263. public function countUnreadRead(): array {
  1264. $sql = <<<'SQL'
  1265. SELECT COUNT(e.id) AS count FROM `_entry` e
  1266. INNER JOIN `_feed` f ON e.id_feed=f.id
  1267. WHERE f.priority > 0
  1268. UNION
  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 AND e.is_read=0
  1272. SQL;
  1273. $res = $this->fetchColumn($sql, 0);
  1274. if ($res === null) {
  1275. return ['all' => -1, 'unread' => -1, 'read' => -1];
  1276. }
  1277. rsort($res);
  1278. $all = (int)($res[0] ?? 0);
  1279. $unread = (int)($res[1] ?? 0);
  1280. return ['all' => $all, 'unread' => $unread, 'read' => $all - $unread];
  1281. }
  1282. public function count(?int $minPriority = null): int {
  1283. $sql = 'SELECT COUNT(e.id) AS count FROM `_entry` e';
  1284. $values = [];
  1285. if ($minPriority !== null) {
  1286. $sql .= ' INNER JOIN `_feed` f ON e.id_feed=f.id';
  1287. $sql .= ' WHERE f.priority > :priority';
  1288. $values[':priority'] = $minPriority;
  1289. }
  1290. $res = $this->fetchColumn($sql, 0, $values);
  1291. return isset($res[0]) ? (int)($res[0]) : -1;
  1292. }
  1293. public function countNotRead(?int $minPriority = null): int {
  1294. $sql = 'SELECT COUNT(e.id) AS count FROM `_entry` e';
  1295. if ($minPriority !== null) {
  1296. $sql .= ' INNER JOIN `_feed` f ON e.id_feed=f.id';
  1297. }
  1298. $sql .= ' WHERE e.is_read=0';
  1299. $values = [];
  1300. if ($minPriority !== null) {
  1301. $sql .= ' AND f.priority > :priority';
  1302. $values[':priority'] = $minPriority;
  1303. }
  1304. $res = $this->fetchColumn($sql, 0, $values);
  1305. return isset($res[0]) ? (int)($res[0]) : -1;
  1306. }
  1307. /** @return array{'all':int,'read':int,'unread':int} */
  1308. public function countUnreadReadFavorites(): array {
  1309. $sql = <<<'SQL'
  1310. SELECT c FROM (
  1311. SELECT COUNT(e1.id) AS c, 1 AS o
  1312. FROM `_entry` AS e1
  1313. JOIN `_feed` AS f1 ON e1.id_feed = f1.id
  1314. WHERE e1.is_favorite = 1
  1315. AND f1.priority >= :priority1
  1316. UNION
  1317. SELECT COUNT(e2.id) AS c, 2 AS o
  1318. FROM `_entry` AS e2
  1319. JOIN `_feed` AS f2 ON e2.id_feed = f2.id
  1320. WHERE e2.is_favorite = 1
  1321. AND e2.is_read = 0 AND f2.priority >= :priority2
  1322. ) u
  1323. ORDER BY o
  1324. SQL;
  1325. //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
  1326. $res = $this->fetchColumn($sql, 0, [
  1327. ':priority1' => FreshRSS_Feed::PRIORITY_CATEGORY,
  1328. ':priority2' => FreshRSS_Feed::PRIORITY_CATEGORY,
  1329. ]);
  1330. if ($res === null) {
  1331. return ['all' => -1, 'unread' => -1, 'read' => -1];
  1332. }
  1333. rsort($res);
  1334. $all = (int)($res[0] ?? 0);
  1335. $unread = (int)($res[1] ?? 0);
  1336. return ['all' => $all, 'unread' => $unread, 'read' => $all - $unread];
  1337. }
  1338. }