EntryDAO.php 67 KB

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