EntryDAO.php 75 KB

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