EntryDAO.php 51 KB

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