EntryDAO.php 48 KB

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