EntryDAO.php 55 KB

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