EntryDAO.php 51 KB

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