EntryDAO.php 49 KB

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