4
0

EntryDAO.php 61 KB

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