EntryDAO.php 50 KB

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