EntryDAO.php 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807
  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. $contentLength = 'LENGTH(' . (static::isCompressed() ? 'content_bin' : 'content') . ') AS content_length';
  755. $hash = static::sqlHexEncode('hash');
  756. $sql = <<<SQL
  757. SELECT id, guid, title, author, {$content}, link, date, `lastSeen`, `lastUserModified`, {$hash} AS hash, is_read, is_favorite, id_feed, tags, attributes,
  758. {$contentLength}
  759. FROM `_entry` WHERE id_feed=:id_feed AND guid=:guid
  760. SQL;
  761. $res = $this->fetchAssoc($sql, [':id_feed' => $id_feed, ':guid' => $guid]);
  762. /** @var list<array{id:string,id_feed:int,guid:string,title:string,author:string,content:string,link:string,date:int,
  763. * is_read:int,is_favorite:int,tags:string,attributes:?string,content_length:int}> $res */
  764. return isset($res[0]) ? FreshRSS_Entry::fromArray($res[0]) : null;
  765. }
  766. public function searchById(string $id): ?FreshRSS_Entry {
  767. $content = static::isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content';
  768. $contentLength = 'LENGTH(' . (static::isCompressed() ? 'content_bin' : 'content') . ') AS content_length';
  769. $hash = static::sqlHexEncode('hash');
  770. $sql = <<<SQL
  771. SELECT id, guid, title, author, {$content}, link, date, `lastSeen`, `lastUserModified`, {$hash} AS hash, is_read, is_favorite, id_feed, tags, attributes,
  772. {$contentLength}
  773. FROM `_entry` WHERE id=:id
  774. SQL;
  775. $res = $this->fetchAssoc($sql, [':id' => $id]);
  776. /** @var list<array{id:string,id_feed:int,guid:string,title:string,author:string,content:string,link:string,date:int,
  777. * is_read:int,is_favorite:int,tags:string,attributes:?string,content_length:int}> $res */
  778. return isset($res[0]) ? FreshRSS_Entry::fromArray($res[0]) : null;
  779. }
  780. public function searchIdByGuid(int $id_feed, string $guid): ?string {
  781. $sql = 'SELECT id FROM `_entry` WHERE id_feed=:id_feed AND guid=:guid';
  782. $res = $this->fetchColumn($sql, 0, [':id_feed' => $id_feed, ':guid' => $guid]);
  783. return empty($res[0]) ? null : (string)($res[0]);
  784. }
  785. /** @return array{0:list<int|string>,1:string} */
  786. public static function sqlBooleanSearch(string $alias, FreshRSS_BooleanSearch $filters, int $level = 0): array {
  787. $search = '';
  788. $values = [];
  789. $isOpen = false;
  790. foreach ($filters->searches() as $filter) {
  791. if ($filter == null) {
  792. continue;
  793. }
  794. if ($filter instanceof FreshRSS_BooleanSearch) {
  795. // BooleanSearches are combined by AND (default) or OR (special case) operator and are recursive
  796. [$filterValues, $filterSearch] = self::sqlBooleanSearch($alias, $filter, $level + 1);
  797. $filterSearch = trim($filterSearch);
  798. if ($filterSearch !== '') {
  799. if ($search !== '') {
  800. $search .= $filter->operator();
  801. } elseif (in_array($filter->operator(), ['AND NOT', 'OR NOT'], true)) {
  802. // Special case if we start with a negation (there is already the default AND before)
  803. $search .= ' NOT';
  804. }
  805. $search .= ' (' . $filterSearch . ') ';
  806. $values = array_merge($values, $filterValues);
  807. }
  808. continue;
  809. }
  810. // Searches are combined by OR and are not recursive
  811. $sub_search = '';
  812. if ($filter->getEntryIds() !== null) {
  813. $sub_search .= 'AND ' . $alias . 'id IN (';
  814. foreach ($filter->getEntryIds() as $entry_id) {
  815. $sub_search .= '?,';
  816. $values[] = $entry_id;
  817. }
  818. $sub_search = rtrim($sub_search, ',');
  819. $sub_search .= ') ';
  820. }
  821. if ($filter->getNotEntryIds() !== null) {
  822. $sub_search .= 'AND ' . $alias . 'id NOT IN (';
  823. foreach ($filter->getNotEntryIds() as $entry_id) {
  824. $sub_search .= '?,';
  825. $values[] = $entry_id;
  826. }
  827. $sub_search = rtrim($sub_search, ',');
  828. $sub_search .= ') ';
  829. }
  830. if ($filter->getMinDate() !== null) {
  831. $sub_search .= 'AND ' . $alias . 'id >= ? ';
  832. $values[] = "{$filter->getMinDate()}000000";
  833. }
  834. if ($filter->getMaxDate() !== null) {
  835. $sub_search .= 'AND ' . $alias . 'id <= ? ';
  836. $values[] = "{$filter->getMaxDate()}000000";
  837. }
  838. if ($filter->getMinPubdate() !== null) {
  839. $sub_search .= 'AND ' . $alias . 'date >= ? ';
  840. $values[] = $filter->getMinPubdate();
  841. }
  842. if ($filter->getMaxPubdate() !== null) {
  843. $sub_search .= 'AND ' . $alias . 'date <= ? ';
  844. $values[] = $filter->getMaxPubdate();
  845. }
  846. if ($filter->getMinUserdate() !== null) {
  847. $sub_search .= 'AND ' . $alias . '`lastUserModified` >= ? ';
  848. $values[] = $filter->getMinUserdate();
  849. }
  850. if ($filter->getMaxUserdate() !== null) {
  851. $sub_search .= 'AND ' . $alias . '`lastUserModified` <= ? ';
  852. $values[] = $filter->getMaxUserdate();
  853. }
  854. //Negation of date intervals must be combined by OR
  855. if ($filter->getNotMinDate() !== null || $filter->getNotMaxDate() !== null) {
  856. $sub_search .= 'AND (';
  857. if ($filter->getNotMinDate() !== null) {
  858. $sub_search .= $alias . 'id < ?';
  859. $values[] = "{$filter->getNotMinDate()}000000";
  860. if ($filter->getNotMaxDate()) {
  861. $sub_search .= ' OR ';
  862. }
  863. }
  864. if ($filter->getNotMaxDate() !== null) {
  865. $sub_search .= $alias . 'id > ?';
  866. $values[] = "{$filter->getNotMaxDate()}000000";
  867. }
  868. $sub_search .= ') ';
  869. }
  870. if ($filter->getNotMinPubdate() !== null || $filter->getNotMaxPubdate() !== null) {
  871. $sub_search .= 'AND (';
  872. if ($filter->getNotMinPubdate() !== null) {
  873. $sub_search .= $alias . 'date < ?';
  874. $values[] = $filter->getNotMinPubdate();
  875. if ($filter->getNotMaxPubdate()) {
  876. $sub_search .= ' OR ';
  877. }
  878. }
  879. if ($filter->getNotMaxPubdate() !== null) {
  880. $sub_search .= $alias . 'date > ?';
  881. $values[] = $filter->getNotMaxPubdate();
  882. }
  883. $sub_search .= ') ';
  884. }
  885. if ($filter->getNotMinUserdate() !== null || $filter->getNotMaxUserdate() !== null) {
  886. $sub_search .= 'AND (';
  887. if ($filter->getNotMinUserdate() !== null) {
  888. $sub_search .= $alias . '`lastUserModified` < ?';
  889. $values[] = $filter->getNotMinUserdate();
  890. if ($filter->getNotMaxUserdate()) {
  891. $sub_search .= ' OR ';
  892. }
  893. }
  894. if ($filter->getNotMaxUserdate() !== null) {
  895. $sub_search .= $alias . '`lastUserModified` > ?';
  896. $values[] = $filter->getNotMaxUserdate();
  897. }
  898. $sub_search .= ') ';
  899. }
  900. if ($filter->getFeedIds() !== null) {
  901. $sub_search .= 'AND ' . $alias . 'id_feed IN (';
  902. foreach ($filter->getFeedIds() as $feed_id) {
  903. $sub_search .= '?,';
  904. $values[] = $feed_id;
  905. }
  906. $sub_search = rtrim($sub_search, ',');
  907. $sub_search .= ') ';
  908. }
  909. if ($filter->getNotFeedIds() !== null) {
  910. $sub_search .= 'AND ' . $alias . 'id_feed NOT IN (';
  911. foreach ($filter->getNotFeedIds() as $feed_id) {
  912. $sub_search .= '?,';
  913. $values[] = $feed_id;
  914. }
  915. $sub_search = rtrim($sub_search, ',');
  916. $sub_search .= ') ';
  917. }
  918. if ($filter->getCategoryIds() !== null) {
  919. $sub_search .= 'AND ' . $alias . 'id_feed IN (SELECT f.id FROM `_feed` f WHERE f.category IN (';
  920. foreach ($filter->getCategoryIds() as $category_id) {
  921. $sub_search .= '?,';
  922. $values[] = $category_id;
  923. }
  924. $sub_search = rtrim($sub_search, ',');
  925. $sub_search .= ')) ';
  926. }
  927. if ($filter->getNotCategoryIds() !== null) {
  928. $sub_search .= 'AND ' . $alias . 'id_feed NOT IN (SELECT f.id FROM `_feed` f WHERE f.category IN (';
  929. foreach ($filter->getNotCategoryIds() as $category_id) {
  930. $sub_search .= '?,';
  931. $values[] = $category_id;
  932. }
  933. $sub_search = rtrim($sub_search, ',');
  934. $sub_search .= ')) ';
  935. }
  936. if ($filter->getLabelIds() !== null) {
  937. foreach ($filter->getLabelIds() as $label_ids) {
  938. if ($label_ids === '*') {
  939. $sub_search .= 'AND EXISTS (SELECT et.id_tag FROM `_entrytag` et WHERE et.id_entry = ' . $alias . 'id) ';
  940. } else {
  941. $sub_search .= 'AND ' . $alias . 'id IN (SELECT et.id_entry FROM `_entrytag` et WHERE et.id_tag IN (';
  942. foreach ($label_ids as $label_id) {
  943. $sub_search .= '?,';
  944. $values[] = $label_id;
  945. }
  946. $sub_search = rtrim($sub_search, ',');
  947. $sub_search .= ')) ';
  948. }
  949. }
  950. }
  951. if ($filter->getNotLabelIds() !== null) {
  952. foreach ($filter->getNotLabelIds() as $label_ids) {
  953. if ($label_ids === '*') {
  954. $sub_search .= 'AND NOT EXISTS (SELECT et.id_tag FROM `_entrytag` et WHERE et.id_entry = ' . $alias . 'id) ';
  955. } else {
  956. $sub_search .= 'AND ' . $alias . 'id NOT IN (SELECT et.id_entry FROM `_entrytag` et WHERE et.id_tag IN (';
  957. foreach ($label_ids as $label_id) {
  958. $sub_search .= '?,';
  959. $values[] = $label_id;
  960. }
  961. $sub_search = rtrim($sub_search, ',');
  962. $sub_search .= ')) ';
  963. }
  964. }
  965. }
  966. if ($filter->getLabelNames() !== null) {
  967. foreach ($filter->getLabelNames() as $label_names) {
  968. $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 (';
  969. foreach ($label_names as $label_name) {
  970. $sub_search .= '?,';
  971. $values[] = $label_name;
  972. }
  973. $sub_search = rtrim($sub_search, ',');
  974. $sub_search .= ')) ';
  975. }
  976. }
  977. if ($filter->getNotLabelNames() !== null) {
  978. foreach ($filter->getNotLabelNames() as $label_names) {
  979. $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 (';
  980. foreach ($label_names as $label_name) {
  981. $sub_search .= '?,';
  982. $values[] = $label_name;
  983. }
  984. $sub_search = rtrim($sub_search, ',');
  985. $sub_search .= ')) ';
  986. }
  987. }
  988. if ($filter->getAuthor() !== null) {
  989. foreach ($filter->getAuthor() as $author) {
  990. $sub_search .= 'AND ' . $alias . 'author LIKE ? ';
  991. $values[] = "%{$author}%";
  992. }
  993. }
  994. if ($filter->getAuthorRegex() !== null) {
  995. foreach ($filter->getAuthorRegex() as $author) {
  996. $sub_search .= 'AND ' . static::sqlRegex("REPLACE({$alias}author, ';', '\n')", $author, $values) . ' ';
  997. }
  998. }
  999. if ($filter->getIntitle() !== null) {
  1000. foreach ($filter->getIntitle() as $title) {
  1001. $sub_search .= 'AND ' . $alias . 'title LIKE ? ';
  1002. $values[] = "%{$title}%";
  1003. }
  1004. }
  1005. if ($filter->getIntitleRegex() !== null) {
  1006. foreach ($filter->getIntitleRegex() as $title) {
  1007. $sub_search .= 'AND ' . static::sqlRegex($alias . 'title', $title, $values) . ' ';
  1008. }
  1009. }
  1010. if ($filter->getIntext() !== null) {
  1011. if (static::isCompressed()) { // MySQL-only
  1012. foreach ($filter->getIntext() as $content) {
  1013. $sub_search .= "AND UNCOMPRESS({$alias}content_bin) LIKE ? ";
  1014. $values[] = "%{$content}%";
  1015. }
  1016. } else {
  1017. foreach ($filter->getIntext() as $content) {
  1018. $sub_search .= 'AND ' . $alias . 'content LIKE ? ';
  1019. $values[] = "%{$content}%";
  1020. }
  1021. }
  1022. }
  1023. if ($filter->getIntextRegex() !== null) {
  1024. if (static::isCompressed()) { // MySQL-only
  1025. foreach ($filter->getIntextRegex() as $content) {
  1026. $sub_search .= 'AND ' . static::sqlRegex("UNCOMPRESS({$alias}content_bin)", $content, $values) . ') ';
  1027. }
  1028. } else {
  1029. foreach ($filter->getIntextRegex() as $content) {
  1030. $sub_search .= 'AND ' . static::sqlRegex($alias . 'content', $content, $values) . ' ';
  1031. }
  1032. }
  1033. }
  1034. if ($filter->getTags() !== null) {
  1035. foreach ($filter->getTags() as $tag) {
  1036. $sub_search .= 'AND ' . static::sqlConcat('TRIM(' . $alias . 'tags) ', " ' #'") . ' LIKE ? ';
  1037. $values[] = "%{$tag} #%";
  1038. }
  1039. }
  1040. if ($filter->getTagsRegex() !== null) {
  1041. foreach ($filter->getTagsRegex() as $tag) {
  1042. $sub_search .= 'AND ' . static::sqlRegex("REPLACE(REPLACE({$alias}tags, ' #', '#'), '#', '\n')", $tag, $values) . ' ';
  1043. }
  1044. }
  1045. if ($filter->getInurl() !== null) {
  1046. foreach ($filter->getInurl() as $url) {
  1047. $sub_search .= 'AND ' . $alias . 'link LIKE ? ';
  1048. $values[] = "%{$url}%";
  1049. }
  1050. }
  1051. if ($filter->getInurlRegex() !== null) {
  1052. foreach ($filter->getInurlRegex() as $url) {
  1053. $sub_search .= 'AND ' . static::sqlRegex($alias . 'link', $url, $values) . ' ';
  1054. }
  1055. }
  1056. if ($filter->getNotAuthor() !== null) {
  1057. foreach ($filter->getNotAuthor() as $author) {
  1058. $sub_search .= 'AND ' . $alias . 'author NOT LIKE ? ';
  1059. $values[] = "%{$author}%";
  1060. }
  1061. }
  1062. if ($filter->getNotAuthorRegex() !== null) {
  1063. foreach ($filter->getNotAuthorRegex() as $author) {
  1064. $sub_search .= 'AND NOT ' . static::sqlRegex("REPLACE({$alias}author, ';', '\n')", $author, $values) . ' ';
  1065. }
  1066. }
  1067. if ($filter->getNotIntitle() !== null) {
  1068. foreach ($filter->getNotIntitle() as $title) {
  1069. $sub_search .= 'AND ' . $alias . 'title NOT LIKE ? ';
  1070. $values[] = "%{$title}%";
  1071. }
  1072. }
  1073. if ($filter->getNotIntitleRegex() !== null) {
  1074. foreach ($filter->getNotIntitleRegex() as $title) {
  1075. $sub_search .= 'AND NOT ' . static::sqlRegex($alias . 'title', $title, $values) . ' ';
  1076. }
  1077. }
  1078. if ($filter->getNotIntext() !== null) {
  1079. if (static::isCompressed()) { // MySQL-only
  1080. foreach ($filter->getNotIntext() as $content) {
  1081. $sub_search .= "AND UNCOMPRESS({$alias}content_bin) NOT LIKE ? ";
  1082. $values[] = "%{$content}%";
  1083. }
  1084. } else {
  1085. foreach ($filter->getNotIntext() as $content) {
  1086. $sub_search .= 'AND ' . $alias . 'content NOT LIKE ? ';
  1087. $values[] = "%{$content}%";
  1088. }
  1089. }
  1090. }
  1091. if ($filter->getNotIntextRegex() !== null) {
  1092. if (static::isCompressed()) { // MySQL-only
  1093. foreach ($filter->getNotIntextRegex() as $content) {
  1094. $sub_search .= 'AND NOT ' . static::sqlRegex("UNCOMPRESS({$alias}content_bin)", $content, $values) . ') ';
  1095. }
  1096. } else {
  1097. foreach ($filter->getNotIntextRegex() as $content) {
  1098. $sub_search .= 'AND NOT ' . static::sqlRegex($alias . 'content', $content, $values) . ' ';
  1099. }
  1100. }
  1101. }
  1102. if ($filter->getNotTags() !== null) {
  1103. foreach ($filter->getNotTags() as $tag) {
  1104. $sub_search .= 'AND ' . static::sqlConcat('TRIM(' . $alias . 'tags) ', " ' #'") . ' NOT LIKE ? ';
  1105. $values[] = "%{$tag} #%";
  1106. }
  1107. }
  1108. if ($filter->getNotTagsRegex() !== null) {
  1109. foreach ($filter->getNotTagsRegex() as $tag) {
  1110. $sub_search .= 'AND NOT ' . static::sqlRegex("REPLACE(REPLACE({$alias}tags, ' #', '#'), '#', '\n')", $tag, $values) . ' ';
  1111. }
  1112. }
  1113. if ($filter->getNotInurl() !== null) {
  1114. foreach ($filter->getNotInurl() as $url) {
  1115. $sub_search .= 'AND ' . $alias . 'link NOT LIKE ? ';
  1116. $values[] = "%{$url}%";
  1117. }
  1118. }
  1119. if ($filter->getNotInurlRegex() !== null) {
  1120. foreach ($filter->getNotInurlRegex() as $url) {
  1121. $sub_search .= 'AND NOT ' . static::sqlRegex($alias . 'link', $url, $values) . ' ';
  1122. }
  1123. }
  1124. if ($filter->getSearch() !== null) {
  1125. foreach ($filter->getSearch() as $search_value) {
  1126. if (static::isCompressed()) { // MySQL-only
  1127. $sub_search .= "AND CONCAT({$alias}title, '\\n', UNCOMPRESS({$alias}content_bin)) LIKE ? ";
  1128. $values[] = "%{$search_value}%";
  1129. } else {
  1130. $sub_search .= 'AND (' . $alias . 'title LIKE ? OR ' . $alias . 'content LIKE ?) ';
  1131. $values[] = "%{$search_value}%";
  1132. $values[] = "%{$search_value}%";
  1133. }
  1134. }
  1135. }
  1136. if ($filter->getSearchRegex() !== null) {
  1137. foreach ($filter->getSearchRegex() as $search_value) {
  1138. if (static::isCompressed()) { // MySQL-only
  1139. $sub_search .= 'AND (' . static::sqlRegex($alias . 'title', $search_value, $values) .
  1140. ' OR ' . static::sqlRegex("UNCOMPRESS({$alias}content_bin)", $search_value, $values) . ') ';
  1141. } else {
  1142. $sub_search .= 'AND (' . static::sqlRegex($alias . 'title', $search_value, $values) .
  1143. ' OR ' . static::sqlRegex($alias . 'content', $search_value, $values) . ') ';
  1144. }
  1145. }
  1146. }
  1147. if ($filter->getNotSearch() !== null) {
  1148. foreach ($filter->getNotSearch() as $search_value) {
  1149. if (static::isCompressed()) { // MySQL-only
  1150. $sub_search .= "AND CONCAT({$alias}title, '\\n', UNCOMPRESS({$alias}content_bin)) NOT LIKE ? ";
  1151. $values[] = "%{$search_value}%";
  1152. } else {
  1153. $sub_search .= 'AND ' . $alias . 'title NOT LIKE ? AND ' . $alias . 'content NOT LIKE ? ';
  1154. $values[] = "%{$search_value}%";
  1155. $values[] = "%{$search_value}%";
  1156. }
  1157. }
  1158. }
  1159. if ($filter->getNotSearchRegex() !== null) {
  1160. foreach ($filter->getNotSearchRegex() as $search_value) {
  1161. if (static::isCompressed()) { // MySQL-only
  1162. $sub_search .= 'AND NOT ' . static::sqlRegex($alias . 'title', $search_value, $values) .
  1163. ' ANT NOT ' . static::sqlRegex("UNCOMPRESS({$alias}content_bin)", $search_value, $values) . ' ';
  1164. } else {
  1165. $sub_search .= 'AND NOT ' . static::sqlRegex($alias . 'title', $search_value, $values) .
  1166. ' AND NOT ' . static::sqlRegex($alias . 'content', $search_value, $values) . ' ';
  1167. }
  1168. }
  1169. }
  1170. if ($sub_search != '') {
  1171. if ($isOpen) {
  1172. $search .= ' OR ';
  1173. } else {
  1174. $isOpen = true;
  1175. }
  1176. // Remove superfluous leading 'AND '
  1177. $search .= '(' . substr($sub_search, 4) . ')';
  1178. }
  1179. }
  1180. return [ $values, $search ];
  1181. }
  1182. /**
  1183. * @param numeric-string $id_min
  1184. * @param numeric-string $id_max
  1185. * @param 'id'|'c.name'|'date'|'f.name'|'link'|'title'|'rand'|'lastUserModified'|'length' $sort
  1186. * @param 'ASC'|'DESC' $order
  1187. * @param numeric-string $continuation_id
  1188. * @param list<string|int> $continuation_values
  1189. * @return array{0:list<int|string>,1:string}
  1190. */
  1191. protected function sqlListEntriesWhere(string $alias = '', int $state = FreshRSS_Entry::STATE_ALL, ?FreshRSS_BooleanSearch $filters = null,
  1192. string $id_min = '0', string $id_max = '0', string $sort = 'id', string $order = 'DESC',
  1193. string $continuation_id = '0', array $continuation_values = []): array {
  1194. $search = ' ';
  1195. $values = [];
  1196. if ($state & FreshRSS_Entry::STATE_ANDS) {
  1197. if ($state & FreshRSS_Entry::STATE_NOT_READ) {
  1198. if (!($state & FreshRSS_Entry::STATE_READ)) {
  1199. $search .= 'AND (' . $alias . 'is_read=0) ';
  1200. }
  1201. } elseif ($state & FreshRSS_Entry::STATE_READ) {
  1202. $search .= 'AND (' . $alias . 'is_read=1) ';
  1203. }
  1204. if ($state & FreshRSS_Entry::STATE_FAVORITE) {
  1205. if (!($state & FreshRSS_Entry::STATE_NOT_FAVORITE)) {
  1206. $search .= 'AND (' . $alias . 'is_favorite=1) ';
  1207. }
  1208. } elseif ($state & FreshRSS_Entry::STATE_NOT_FAVORITE) {
  1209. $search .= 'AND (' . $alias . 'is_favorite=0) ';
  1210. }
  1211. }
  1212. if ($state & FreshRSS_Entry::STATE_ORS) {
  1213. if (trim($search) === '') {
  1214. $search = 'AND (1=0) ';
  1215. }
  1216. if ($state & FreshRSS_Entry::STATE_OR_NOT_READ) {
  1217. $search = rtrim($search, ') ');
  1218. $search .= ' OR ' . $alias . 'is_read=0) ';
  1219. }
  1220. if ($state & FreshRSS_Entry::STATE_OR_FAVORITE) {
  1221. $search = rtrim($search, ') ');
  1222. $search .= ' OR ' . $alias . 'is_favorite=1) ';
  1223. }
  1224. }
  1225. if (!ctype_digit($id_min)) {
  1226. $id_min = '0';
  1227. }
  1228. if (!ctype_digit($id_max)) {
  1229. $id_max = '0';
  1230. }
  1231. if (!ctype_digit($continuation_id)) {
  1232. $continuation_id = '0';
  1233. }
  1234. if ($continuation_id !== '0' && $sort === 'id') {
  1235. if ($order === 'ASC') {
  1236. $id_min = $id_min === '0' ? $continuation_id : max($id_min, $continuation_id);
  1237. } else {
  1238. $id_max = $id_max === '0' ? $continuation_id : min($id_max, $continuation_id);
  1239. }
  1240. }
  1241. if ($id_max !== '0') {
  1242. $search .= 'AND ' . $alias . 'id <= ? ';
  1243. $values[] = $id_max;
  1244. }
  1245. if ($id_min !== '0') {
  1246. $search .= 'AND ' . $alias . 'id >= ? ';
  1247. $values[] = $id_min;
  1248. }
  1249. if ($continuation_id !== '0' && in_array($sort, ['c.name', 'date', 'f.name', 'link', 'title', 'lastUserModified', 'length'], true)) {
  1250. $sign = $order === 'ASC' ? '>' : '<';
  1251. $orderBy = match ($sort) {
  1252. 'c.name' => 'c.name',
  1253. 'f.name' => 'f.name',
  1254. 'lastUserModified' => $alias . '`lastUserModified`',
  1255. 'length' => 'LENGTH(' . $alias . (static::isCompressed() ? 'content_bin' : 'content') . ')',
  1256. default => $alias . $sort,
  1257. };
  1258. // Keyset pagination (Compatibility syntax due to poor performance of tuple syntax in MySQL https://bugs.mysql.com/bug.php?id=104128)
  1259. if ($sort === 'c.name') {
  1260. // Includes a secondary sort by feed name
  1261. $search .= "AND ((c.name {$sign} ?) OR (c.name = ? AND f.name {$sign} ?) OR (c.name = ? AND f.name = ? AND {$alias}id {$sign}= ?)) ";
  1262. $values[] = $continuation_values[0];
  1263. $values[] = $continuation_values[0];
  1264. $values[] = $continuation_values[1];
  1265. $values[] = $continuation_values[0];
  1266. $values[] = $continuation_values[1];
  1267. $values[] = $continuation_id;
  1268. } else {
  1269. $search .= "AND ({$orderBy} {$sign} ? OR ({$orderBy} = ? AND {$alias}id {$sign}= ?)) ";
  1270. $values[] = $continuation_values[0];
  1271. $values[] = $continuation_values[0];
  1272. $values[] = $continuation_id;
  1273. }
  1274. }
  1275. if ($filters !== null && count($filters->searches()) > 0) {
  1276. [$filterValues, $filterSearch] = self::sqlBooleanSearch($alias, $filters);
  1277. $filterSearch = trim($filterSearch);
  1278. if ($filterSearch !== '') {
  1279. $search .= 'AND (' . $filterSearch . ') ';
  1280. $values = array_merge($values, $filterValues);
  1281. $this->registerSqlFunctions($search);
  1282. }
  1283. }
  1284. return [$values, $search];
  1285. }
  1286. /**
  1287. * @param 'a'|'A'|'i'|'s'|'S'|'c'|'f'|'t'|'T'|'ST'|'Z' $type
  1288. * @param int $id category/feed/tag ID
  1289. * @param numeric-string $id_min
  1290. * @param numeric-string $id_max
  1291. * @param 'id'|'c.name'|'date'|'f.name'|'link'|'title'|'rand'|'lastUserModified'|'length' $sort
  1292. * @param 'ASC'|'DESC' $order
  1293. * @param numeric-string $continuation_id
  1294. * @param list<string|int> $continuation_values
  1295. * @return array{0:list<int|string>,1:string}
  1296. * @throws FreshRSS_EntriesGetter_Exception
  1297. */
  1298. private function sqlListWhere(string $type = 'a', int $id = 0, int $state = FreshRSS_Entry::STATE_ALL, ?FreshRSS_BooleanSearch $filters = null,
  1299. string $id_min = '0', string $id_max = '0', string $sort = 'id', string $order = 'DESC',
  1300. string $continuation_id = '0', array $continuation_values = [], int $limit = 1, int $offset = 0): array {
  1301. if (!$state) {
  1302. $state = FreshRSS_Entry::STATE_ALL;
  1303. }
  1304. $where = '';
  1305. $values = [];
  1306. switch ($type) {
  1307. case 'a': // All PRIORITY_MAIN_STREAM
  1308. $where .= 'f.priority >= ' . FreshRSS_Feed::PRIORITY_MAIN_STREAM . ' ';
  1309. break;
  1310. case 'A': // All except PRIORITY_HIDDEN
  1311. $where .= 'f.priority >= ' . FreshRSS_Feed::PRIORITY_FEED . ' ';
  1312. break;
  1313. case 'Z': // All including PRIORITY_HIDDEN
  1314. $where .= 'f.priority >= ' . FreshRSS_Feed::PRIORITY_HIDDEN . ' ';
  1315. break;
  1316. case 'i': // Priority important feeds
  1317. $where .= 'f.priority >= ' . FreshRSS_Feed::PRIORITY_IMPORTANT . ' ';
  1318. break;
  1319. case 's': //Starred. Deprecated: use $state instead
  1320. $where .= 'f.priority > ' . FreshRSS_Feed::PRIORITY_HIDDEN . ' ';
  1321. $where .= 'AND e.is_favorite=1 ';
  1322. break;
  1323. case 'S': //Starred
  1324. $where .= 'e.is_favorite=1 ';
  1325. break;
  1326. case 'c': //Category
  1327. $where .= 'f.priority >= ' . FreshRSS_Feed::PRIORITY_CATEGORY . ' ';
  1328. $where .= 'AND f.category=? ';
  1329. $values[] = $id;
  1330. break;
  1331. case 'f': //Feed
  1332. $where .= 'e.id_feed=? ';
  1333. $values[] = $id;
  1334. break;
  1335. case 't': //Tag (label)
  1336. $where .= 'et.id_tag=? ';
  1337. $values[] = $id;
  1338. break;
  1339. case 'T': //Any tag (label)
  1340. $where .= '1=1 ';
  1341. break;
  1342. case 'ST': //Starred or tagged (label)
  1343. $where .= 'e.is_favorite=1 OR EXISTS (SELECT et2.id_tag FROM `_entrytag` et2 WHERE et2.id_entry = e.id) ';
  1344. break;
  1345. default:
  1346. throw new FreshRSS_EntriesGetter_Exception('Bad type in Entry->listByType: [' . $type . ']!');
  1347. }
  1348. $order = in_array($order, ['ASC', 'DESC'], true) ? $order : 'DESC';
  1349. $sort = in_array($sort, ['id', 'c.name', 'date', 'f.name', 'link', 'title', 'rand', 'lastUserModified', 'length'], true) ? $sort : 'id';
  1350. $orderBy = match ($sort) {
  1351. 'c.name' => 'c.name',
  1352. 'f.name' => 'f.name',
  1353. 'lastUserModified' => 'e.`lastUserModified`',
  1354. 'length' => 'LENGTH(e.' . (static::isCompressed() ? 'content_bin' : 'content') . ')',
  1355. 'rand' => static::sqlRandom(),
  1356. default => 'e.' . $sort,
  1357. };
  1358. [$searchValues, $search] = $this->sqlListEntriesWhere(alias: 'e.', state: $state, filters: $filters, id_min: $id_min, id_max: $id_max,
  1359. sort: $sort, order: $order, continuation_id: $continuation_id, continuation_values: $continuation_values);
  1360. return [array_merge($values, $searchValues), 'SELECT '
  1361. . ($type === 'T' ? 'DISTINCT ' : '')
  1362. . 'e.id'
  1363. . ($type === 'T' && $sort !== 'id' ? ', ' . $orderBy : '') // SELECT DISTINCT, ORDER BY expressions must appear in SELECT
  1364. . ' FROM `_entry` e '
  1365. . 'INNER JOIN `_feed` f ON f.id = e.id_feed '
  1366. . ($sort === 'c.name' ? 'INNER JOIN `_category` c ON c.id = f.category ' : '')
  1367. . ($type === 't' || $type === 'T' ? 'INNER JOIN `_entrytag` et ON et.id_entry = e.id ' : '')
  1368. . 'WHERE ' . $where
  1369. . $search
  1370. . 'ORDER BY ' . $orderBy . ' ' . $order
  1371. . ($sort === 'c.name' ? ', f.name ' . $order : '') // Secondary sort
  1372. . ($sort === 'id' ? '' : ', e.id ' . $order) // For keyset pagination
  1373. . ($limit > 0 ? ' LIMIT ' . $limit : '') // http://explainextended.com/2009/10/23/mysql-order-by-limit-performance-late-row-lookups/
  1374. . ($offset > 0 ? ' OFFSET ' . $offset : '')
  1375. ];
  1376. }
  1377. /**
  1378. * @param 'a'|'A'|'s'|'S'|'i'|'c'|'f'|'t'|'T'|'ST'|'Z' $type
  1379. * @param int $id category/feed/tag ID
  1380. * @param numeric-string $id_min
  1381. * @param numeric-string $id_max
  1382. * @param 'id'|'c.name'|'date'|'f.name'|'link'|'title'|'rand'|'lastUserModified'|'length' $sort
  1383. * @param 'ASC'|'DESC' $order
  1384. * @param numeric-string $continuation_id
  1385. * @param list<string|int> $continuation_values
  1386. * @throws FreshRSS_EntriesGetter_Exception
  1387. */
  1388. private function listWhereRaw(string $type = 'a', int $id = 0, int $state = FreshRSS_Entry::STATE_ALL, ?FreshRSS_BooleanSearch $filters = null,
  1389. string $id_min = '0', string $id_max = '0', string $sort = 'id', string $order = 'DESC',
  1390. string $continuation_id = '0', array $continuation_values = [], int $limit = 1, int $offset = 0): PDOStatement|false {
  1391. $order = in_array($order, ['ASC', 'DESC'], true) ? $order : 'DESC';
  1392. $sort = in_array($sort, ['id', 'c.name', 'date', 'f.name', 'link', 'title', 'rand', 'lastUserModified', 'length'], true) ? $sort : 'id';
  1393. [$values, $sql] = $this->sqlListWhere($type, $id, $state, $filters, id_min: $id_min, id_max: $id_max, sort: $sort, order: $order,
  1394. continuation_id: $continuation_id, continuation_values: $continuation_values, limit: $limit, offset: $offset);
  1395. $orderBy = match ($sort) {
  1396. 'c.name' => 'c0.name',
  1397. 'f.name' => 'f0.name',
  1398. 'lastUserModified' => 'e0.`lastUserModified`',
  1399. 'length' => 'LENGTH(e0.' . (static::isCompressed() ? 'content_bin' : 'content') . ')',
  1400. 'rand' => static::sqlRandom(),
  1401. default => 'e0.' . $sort,
  1402. };
  1403. $content = static::isCompressed() ? 'UNCOMPRESS(e0.content_bin) AS content' : 'e0.content';
  1404. $hash = static::sqlHexEncode('e0.hash');
  1405. $sql = <<<SQL
  1406. SELECT e0.id, e0.guid, e0.title, e0.author, {$content}, e0.link,
  1407. e0.date, e0.`lastSeen`, e0.`lastUserModified`, {$hash} AS hash, e0.is_read, e0.is_favorite, e0.id_feed, e0.tags, e0.attributes
  1408. FROM `_entry` e0 INNER JOIN ({$sql}) e2 ON e2.id=e0.id
  1409. SQL;
  1410. if ($sort === 'f.name' || $sort === 'c.name') {
  1411. $sql .= ' INNER JOIN `_feed` f0 ON f0.id = e0.id_feed ';
  1412. }
  1413. if ($sort === 'c.name') {
  1414. $sql .= ' INNER JOIN `_category` c0 ON c0.id = f0.category ';
  1415. }
  1416. $sql .= ' ORDER BY ' . $orderBy . ' ' . $order;
  1417. if ($sort === 'c.name') {
  1418. $sql .= ', f0.name ' . $order; // Secondary sort
  1419. }
  1420. if ($sort !== 'id') {
  1421. // For keyset pagination
  1422. $sql .= ', e0.id ' . $order;
  1423. }
  1424. $stm = $this->pdo->prepare($sql);
  1425. if ($stm !== false && $stm->execute($values)) {
  1426. return $stm;
  1427. } else {
  1428. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  1429. /** @var array{0:string,1:int,2:string} $info */
  1430. if ($this->autoUpdateDb($info)) {
  1431. return $this->listWhereRaw($type, $id, $state, $filters, id_min: $id_min, id_max: $id_max, sort: $sort, order: $order,
  1432. continuation_id: $continuation_id, continuation_values: $continuation_values, limit: $limit, offset: $offset);
  1433. }
  1434. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  1435. return false;
  1436. }
  1437. }
  1438. /**
  1439. * @param 'a'|'A'|'s'|'S'|'i'|'c'|'f'|'t'|'T'|'ST'|'Z' $type
  1440. * @param int $id category/feed/tag ID
  1441. * @param numeric-string $id_min
  1442. * @param numeric-string $id_max
  1443. * @param 'id'|'c.name'|'date'|'f.name'|'link'|'title'|'rand'|'lastUserModified'|'length' $sort
  1444. * @param 'ASC'|'DESC' $order
  1445. * @param numeric-string $continuation_id
  1446. * @param list<string|int> $continuation_values
  1447. * @return Traversable<FreshRSS_Entry>
  1448. * @throws FreshRSS_EntriesGetter_Exception
  1449. */
  1450. public function listWhere(string $type = 'a', int $id = 0, int $state = FreshRSS_Entry::STATE_ALL, ?FreshRSS_BooleanSearch $filters = null,
  1451. string $id_min = '0', string $id_max = '0', string $sort = 'id', string $order = 'DESC',
  1452. string $continuation_id = '0', array $continuation_values = [], int $limit = 1, int $offset = 0): Traversable {
  1453. $stm = $this->listWhereRaw($type, $id, $state, $filters, id_min: $id_min, id_max: $id_max, sort: $sort, order: $order,
  1454. continuation_id: $continuation_id, continuation_values: $continuation_values, limit: $limit, offset: $offset);
  1455. if ($stm !== false) {
  1456. while (is_array($row = $stm->fetch(PDO::FETCH_ASSOC))) {
  1457. /** @var array{'id':string,'id_feed':int,'guid':string,'title':string,'author':string,'content':string,'link':string,'date':int,
  1458. * 'hash':string,'is_read':int,'is_favorite':int,'tags':string,'attributes'?:?string} $row */
  1459. yield FreshRSS_Entry::fromArray($row);
  1460. }
  1461. }
  1462. }
  1463. /**
  1464. * For API.
  1465. * @param array<numeric-string> $ids
  1466. * @param 'ASC'|'DESC' $order
  1467. * @return Traversable<FreshRSS_Entry>
  1468. */
  1469. public function listByIds(array $ids, string $order = 'DESC'): Traversable {
  1470. if (count($ids) < 1) {
  1471. return;
  1472. }
  1473. if (count($ids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  1474. // Split a query with too many variables parameters
  1475. $idsChunks = array_chunk($ids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  1476. foreach ($idsChunks as $idsChunk) {
  1477. foreach ($this->listByIds($idsChunk, order: $order) as $entry) {
  1478. yield $entry;
  1479. }
  1480. }
  1481. return;
  1482. }
  1483. $order = in_array($order, ['ASC', 'DESC'], true) ? $order : 'DESC';
  1484. $content = static::isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content';
  1485. $hash = static::sqlHexEncode('hash');
  1486. $repeats = str_repeat('?,', count($ids) - 1) . '?';
  1487. $sql = <<<SQL
  1488. SELECT id, guid, title, author, link, date, {$hash} AS hash, is_read, is_favorite, id_feed, tags, attributes, {$content}, `lastUserModified`
  1489. FROM `_entry`
  1490. WHERE id IN ({$repeats})
  1491. ORDER BY id {$order}
  1492. SQL;
  1493. $stm = $this->pdo->prepare($sql);
  1494. if ($stm === false || !$stm->execute($ids)) {
  1495. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  1496. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  1497. return;
  1498. }
  1499. while (is_array($row = $stm->fetch(PDO::FETCH_ASSOC))) {
  1500. /** @var array{'id':string,'id_feed':int,'guid':string,'title':string,'author':string,'content':string,'link':string,'date':int,
  1501. * 'hash':string,'is_read':int,'is_favorite':int,'tags':string,'attributes':?string} $row */
  1502. yield FreshRSS_Entry::fromArray($row);
  1503. }
  1504. }
  1505. /**
  1506. * @param 'a'|'A'|'s'|'S'|'c'|'f'|'t'|'T'|'ST'|'Z' $type
  1507. * @param int $id category/feed/tag ID
  1508. * @param numeric-string $id_min
  1509. * @param numeric-string $id_max
  1510. * @param 'ASC'|'DESC' $order
  1511. * @param numeric-string $continuation_id
  1512. * @param list<string|int> $continuation_values
  1513. * @return list<numeric-string>|null
  1514. * @throws FreshRSS_EntriesGetter_Exception
  1515. */
  1516. public function listIdsWhere(string $type = 'a', int $id = 0, int $state = FreshRSS_Entry::STATE_ALL, ?FreshRSS_BooleanSearch $filters = null,
  1517. string $id_min = '0', string $id_max = '0', string $order = 'DESC',
  1518. string $continuation_id = '0', array $continuation_values = [], int $limit = 1, int $offset = 0): ?array {
  1519. [$values, $sql] = $this->sqlListWhere($type, $id, $state, $filters, id_min: $id_min, id_max: $id_max, order: $order,
  1520. continuation_id: $continuation_id, continuation_values: $continuation_values, limit: $limit, offset: $offset);
  1521. $stm = $this->pdo->prepare($sql);
  1522. if ($stm !== false && $stm->execute($values)) {
  1523. /** @var list<int|numeric-string> $res */
  1524. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  1525. $res = array_map('strval', $res);
  1526. /** @var list<numeric-string> $res */
  1527. return $res;
  1528. }
  1529. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  1530. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  1531. return null;
  1532. }
  1533. /**
  1534. * @param array<string> $guids
  1535. * @return array<string,string> guid => hash
  1536. */
  1537. public function listHashForFeedGuids(int $id_feed, array $guids): array {
  1538. $result = [];
  1539. if (count($guids) < 1) {
  1540. return $result;
  1541. } elseif (count($guids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  1542. // Split a query with too many variables parameters
  1543. $guidsChunks = array_chunk($guids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  1544. foreach ($guidsChunks as $guidsChunk) {
  1545. $result += $this->listHashForFeedGuids($id_feed, $guidsChunk);
  1546. }
  1547. return $result;
  1548. }
  1549. $guids = array_unique($guids);
  1550. $sql = 'SELECT guid, ' . static::sqlHexEncode('hash') .
  1551. ' AS hex_hash FROM `_entry` WHERE id_feed=? AND guid IN (' . str_repeat('?,', count($guids) - 1) . '?)';
  1552. $stm = $this->pdo->prepare($sql);
  1553. $values = [$id_feed];
  1554. $values = array_merge($values, $guids);
  1555. if ($stm !== false && $stm->execute($values)) {
  1556. $rows = $stm->fetchAll(PDO::FETCH_ASSOC);
  1557. foreach ($rows as $row) {
  1558. /** @var array{guid:string,hex_hash:string} $row */
  1559. $result[$row['guid']] = $row['hex_hash'];
  1560. }
  1561. return $result;
  1562. } else {
  1563. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  1564. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info)
  1565. . ' while querying feed ' . $id_feed);
  1566. return [];
  1567. }
  1568. }
  1569. /**
  1570. * @param array<string> $guids
  1571. * @return int|false The number of affected entries, or false if error
  1572. */
  1573. public function updateLastSeen(int $id_feed, array $guids, int $mtime = 0): int|false {
  1574. if (count($guids) < 1) {
  1575. return 0;
  1576. } elseif (count($guids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  1577. // Split a query with too many variables parameters
  1578. $affected = 0;
  1579. $guidsChunks = array_chunk($guids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  1580. foreach ($guidsChunks as $guidsChunk) {
  1581. $affected += ($this->updateLastSeen($id_feed, $guidsChunk, $mtime) ?: 0);
  1582. }
  1583. return $affected;
  1584. }
  1585. $sql = 'UPDATE `_entry` SET `lastSeen`=? WHERE id_feed=? AND guid IN (' . str_repeat('?,', count($guids) - 1) . '?)';
  1586. $stm = $this->pdo->prepare($sql);
  1587. if ($mtime <= 0) {
  1588. $mtime = time();
  1589. }
  1590. $values = [$mtime, $id_feed];
  1591. $values = array_merge($values, $guids);
  1592. if ($stm !== false && $stm->execute($values)) {
  1593. return $stm->rowCount();
  1594. } else {
  1595. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  1596. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info)
  1597. . ' while updating feed ' . $id_feed);
  1598. return false;
  1599. }
  1600. }
  1601. /**
  1602. * Update (touch) the last seen attribute of the latest entries of a given feed.
  1603. * Useful when a feed is unchanged / cached.
  1604. * To be performed just before {@see FreshRSS_FeedDAO::updateLastUpdate()}
  1605. * @return int|false The number of affected entries, or false in case of error
  1606. */
  1607. public function updateLastSeenUnchanged(int $id_feed, int $mtime = 0): int|false {
  1608. $sql = <<<'SQL'
  1609. UPDATE `_entry` SET `lastSeen` = :mtime
  1610. WHERE id_feed = :id_feed1 AND `lastSeen` = (
  1611. SELECT `lastUpdate` FROM `_feed` f
  1612. WHERE f.id = :id_feed2
  1613. )
  1614. SQL;
  1615. $stm = $this->pdo->prepare($sql);
  1616. if ($mtime <= 0) {
  1617. $mtime = time();
  1618. }
  1619. if ($stm !== false &&
  1620. $stm->bindValue(':mtime', $mtime, PDO::PARAM_INT) &&
  1621. $stm->bindValue(':id_feed1', $id_feed, PDO::PARAM_INT) &&
  1622. $stm->bindValue(':id_feed2', $id_feed, PDO::PARAM_INT) &&
  1623. $stm->execute()) {
  1624. return $stm->rowCount();
  1625. } else {
  1626. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  1627. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info) . ' while updating feed ' . $id_feed);
  1628. return false;
  1629. }
  1630. }
  1631. /** @return array<string,int> */
  1632. public function countUnreadRead(): array {
  1633. $sql = <<<'SQL'
  1634. SELECT COUNT(e.id) AS count FROM `_entry` e
  1635. INNER JOIN `_feed` f ON e.id_feed=f.id
  1636. WHERE f.priority > 0
  1637. UNION
  1638. SELECT COUNT(e.id) AS count FROM `_entry` e
  1639. INNER JOIN `_feed` f ON e.id_feed=f.id
  1640. WHERE f.priority > 0 AND e.is_read=0
  1641. SQL;
  1642. $res = $this->fetchColumn($sql, 0);
  1643. if ($res === null) {
  1644. return ['all' => -1, 'unread' => -1, 'read' => -1];
  1645. }
  1646. rsort($res);
  1647. $all = (int)($res[0] ?? 0);
  1648. $unread = (int)($res[1] ?? 0);
  1649. return ['all' => $all, 'unread' => $unread, 'read' => $all - $unread];
  1650. }
  1651. public function count(?int $minPriority = null): int {
  1652. $sql = 'SELECT COUNT(e.id) AS count FROM `_entry` e';
  1653. $values = [];
  1654. if ($minPriority !== null) {
  1655. $sql .= ' INNER JOIN `_feed` f ON e.id_feed=f.id';
  1656. $sql .= ' WHERE f.priority > :priority';
  1657. $values[':priority'] = $minPriority;
  1658. }
  1659. $res = $this->fetchColumn($sql, 0, $values);
  1660. return isset($res[0]) ? (int)($res[0]) : -1;
  1661. }
  1662. public function countNotRead(?int $minPriority = null): int {
  1663. $sql = 'SELECT COUNT(e.id) AS count FROM `_entry` e';
  1664. if ($minPriority !== null) {
  1665. $sql .= ' INNER JOIN `_feed` f ON e.id_feed=f.id';
  1666. }
  1667. $sql .= ' WHERE e.is_read=0';
  1668. $values = [];
  1669. if ($minPriority !== null) {
  1670. $sql .= ' AND f.priority > :priority';
  1671. $values[':priority'] = $minPriority;
  1672. }
  1673. $res = $this->fetchColumn($sql, 0, $values);
  1674. return isset($res[0]) ? (int)($res[0]) : -1;
  1675. }
  1676. /** @return array{'all':int,'read':int,'unread':int} */
  1677. public function countUnreadReadFavorites(): array {
  1678. $sql = <<<'SQL'
  1679. SELECT c FROM (
  1680. SELECT COUNT(e1.id) AS c, 1 AS o
  1681. FROM `_entry` AS e1
  1682. JOIN `_feed` AS f1 ON e1.id_feed = f1.id
  1683. WHERE e1.is_favorite = 1
  1684. AND f1.priority >= :priority1
  1685. UNION
  1686. SELECT COUNT(e2.id) AS c, 2 AS o
  1687. FROM `_entry` AS e2
  1688. JOIN `_feed` AS f2 ON e2.id_feed = f2.id
  1689. WHERE e2.is_favorite = 1
  1690. AND e2.is_read = 0 AND f2.priority >= :priority2
  1691. ) u
  1692. ORDER BY o
  1693. SQL;
  1694. //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
  1695. $res = $this->fetchColumn($sql, 0, [
  1696. ':priority1' => FreshRSS_Feed::PRIORITY_CATEGORY,
  1697. ':priority2' => FreshRSS_Feed::PRIORITY_CATEGORY,
  1698. ]);
  1699. if ($res === null) {
  1700. return ['all' => -1, 'unread' => -1, 'read' => -1];
  1701. }
  1702. rsort($res);
  1703. $all = (int)($res[0] ?? 0);
  1704. $unread = (int)($res[1] ?? 0);
  1705. return ['all' => $all, 'unread' => $unread, 'read' => $all - $unread];
  1706. }
  1707. }