EntryDAO.php 66 KB

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