EntryDAO.php 72 KB

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