EntryDAO.php 52 KB

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