EntryDAO.php 49 KB

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