EntryDAO.php 74 KB

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