4
0

EntryDAO.php 56 KB

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