EntryDAO.php 51 KB

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