EntryDAO.php 49 KB

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