EntryDAO.php 76 KB

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