EntryDAO.php 64 KB

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