EntryDAO.php 51 KB

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