EntryDAO.php 65 KB

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