EntryDAO.php 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366
  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 addEntry: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
  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 updateEntry: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
  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 && $stm->execute($values)) {
  313. return $stm->rowCount();
  314. } else {
  315. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  316. Minz_Log::error('SQL error markFavorite: ' . $info[2]);
  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 = 'UPDATE `_feed` f '
  329. . 'LEFT OUTER JOIN ('
  330. . 'SELECT e.id_feed, '
  331. . 'COUNT(*) AS nbUnreads '
  332. . 'FROM `_entry` e '
  333. . 'WHERE e.is_read=0 '
  334. . 'GROUP BY e.id_feed'
  335. . ') x ON x.id_feed=f.id '
  336. . 'SET f.`cache_nbUnreads`=COALESCE(x.nbUnreads, 0)';
  337. $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 && $stm->execute($values)) {
  353. return true;
  354. } else {
  355. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  356. Minz_Log::error('SQL error updateCacheUnreads: ' . $info[2]);
  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 markRead: ' . $info[2]);
  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 && $stm->execute($values)) {
  415. return $stm->rowCount();
  416. } else {
  417. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  418. Minz_Log::error('SQL error markRead: ' . $info[2]);
  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 markReadEntries: ' . $info[2]);
  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 markReadCat: ' . $info[2]);
  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 markReadFeed: ' . $info[2] . ' 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 markReadFeed cache: ' . $info[2]);
  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 markReadTag: ' . $info[2]);
  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 && $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. // un guid est unique pour un flux donné
  670. $sql = 'SELECT id, guid, title, author, '
  671. . (static::isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  672. . ', link, date, is_read, is_favorite, id_feed, tags, attributes '
  673. . 'FROM `_entry` WHERE id_feed=:id_feed AND guid=:guid';
  674. $stm = $this->pdo->prepare($sql);
  675. $stm->bindParam(':id_feed', $id_feed, PDO::PARAM_INT);
  676. $stm->bindParam(':guid', $guid);
  677. $stm->execute();
  678. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  679. return isset($res[0]) ? FreshRSS_Entry::fromArray($res[0]) : null;
  680. }
  681. public function searchById(string $id): ?FreshRSS_Entry {
  682. $sql = 'SELECT id, guid, title, author, '
  683. . (static::isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  684. . ', link, date, is_read, is_favorite, id_feed, tags, attributes '
  685. . 'FROM `_entry` WHERE id=:id';
  686. $stm = $this->pdo->prepare($sql);
  687. $stm->bindParam(':id', $id, PDO::PARAM_INT);
  688. $stm->execute();
  689. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  690. return isset($res[0]) ? FreshRSS_Entry::fromArray($res[0]) : null;
  691. }
  692. public function searchIdByGuid(int $id_feed, string $guid): ?string {
  693. $sql = 'SELECT id FROM `_entry` WHERE id_feed=:id_feed AND guid=:guid';
  694. $stm = $this->pdo->prepare($sql);
  695. $stm->bindParam(':id_feed', $id_feed, PDO::PARAM_INT);
  696. $stm->bindParam(':guid', $guid);
  697. $stm->execute();
  698. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  699. return isset($res[0]) ? $res[0] : null;
  700. }
  701. /** @return array{0:array<int|string>,1:string} */
  702. public static function sqlBooleanSearch(string $alias, FreshRSS_BooleanSearch $filters, int $level = 0): array {
  703. $search = '';
  704. $values = [];
  705. $isOpen = false;
  706. foreach ($filters->searches() as $filter) {
  707. if ($filter == null) {
  708. continue;
  709. }
  710. if ($filter instanceof FreshRSS_BooleanSearch) {
  711. // BooleanSearches are combined by AND (default) or OR (special case) operator and are recursive
  712. list($filterValues, $filterSearch) = self::sqlBooleanSearch($alias, $filter, $level + 1);
  713. $filterSearch = trim($filterSearch);
  714. if ($filterSearch !== '') {
  715. if ($search !== '') {
  716. $search .= $filter->operator();
  717. } elseif ($filter->operator() === 'AND NOT') {
  718. // Special case if we start with a negation (there is already the default AND before)
  719. $search .= ' NOT';
  720. }
  721. $search .= ' (' . $filterSearch . ') ';
  722. $values = array_merge($values, $filterValues);
  723. }
  724. continue;
  725. }
  726. // Searches are combined by OR and are not recursive
  727. $sub_search = '';
  728. if ($filter->getEntryIds()) {
  729. $sub_search .= 'AND ' . $alias . 'id IN (';
  730. foreach ($filter->getEntryIds() as $entry_id) {
  731. $sub_search .= '?,';
  732. $values[] = $entry_id;
  733. }
  734. $sub_search = rtrim($sub_search, ',');
  735. $sub_search .= ') ';
  736. }
  737. if ($filter->getNotEntryIds()) {
  738. $sub_search .= 'AND ' . $alias . 'id NOT IN (';
  739. foreach ($filter->getNotEntryIds() as $entry_id) {
  740. $sub_search .= '?,';
  741. $values[] = $entry_id;
  742. }
  743. $sub_search = rtrim($sub_search, ',');
  744. $sub_search .= ') ';
  745. }
  746. if ($filter->getMinDate()) {
  747. $sub_search .= 'AND ' . $alias . 'id >= ? ';
  748. $values[] = "{$filter->getMinDate()}000000";
  749. }
  750. if ($filter->getMaxDate()) {
  751. $sub_search .= 'AND ' . $alias . 'id <= ? ';
  752. $values[] = "{$filter->getMaxDate()}000000";
  753. }
  754. if ($filter->getMinPubdate()) {
  755. $sub_search .= 'AND ' . $alias . 'date >= ? ';
  756. $values[] = $filter->getMinPubdate();
  757. }
  758. if ($filter->getMaxPubdate()) {
  759. $sub_search .= 'AND ' . $alias . 'date <= ? ';
  760. $values[] = $filter->getMaxPubdate();
  761. }
  762. //Negation of date intervals must be combined by OR
  763. if ($filter->getNotMinDate() || $filter->getNotMaxDate()) {
  764. $sub_search .= 'AND (';
  765. if ($filter->getNotMinDate()) {
  766. $sub_search .= $alias . 'id < ?';
  767. $values[] = "{$filter->getNotMinDate()}000000";
  768. if ($filter->getNotMaxDate()) {
  769. $sub_search .= ' OR ';
  770. }
  771. }
  772. if ($filter->getNotMaxDate()) {
  773. $sub_search .= $alias . 'id > ?';
  774. $values[] = "{$filter->getNotMaxDate()}000000";
  775. }
  776. $sub_search .= ') ';
  777. }
  778. if ($filter->getNotMinPubdate() || $filter->getNotMaxPubdate()) {
  779. $sub_search .= 'AND (';
  780. if ($filter->getNotMinPubdate()) {
  781. $sub_search .= $alias . 'date < ?';
  782. $values[] = $filter->getNotMinPubdate();
  783. if ($filter->getNotMaxPubdate()) {
  784. $sub_search .= ' OR ';
  785. }
  786. }
  787. if ($filter->getNotMaxPubdate()) {
  788. $sub_search .= $alias . 'date > ?';
  789. $values[] = $filter->getNotMaxPubdate();
  790. }
  791. $sub_search .= ') ';
  792. }
  793. if ($filter->getFeedIds()) {
  794. $sub_search .= 'AND ' . $alias . 'id_feed IN (';
  795. foreach ($filter->getFeedIds() as $feed_id) {
  796. $sub_search .= '?,';
  797. $values[] = $feed_id;
  798. }
  799. $sub_search = rtrim($sub_search, ',');
  800. $sub_search .= ') ';
  801. }
  802. if ($filter->getNotFeedIds()) {
  803. $sub_search .= 'AND ' . $alias . 'id_feed NOT IN (';
  804. foreach ($filter->getNotFeedIds() as $feed_id) {
  805. $sub_search .= '?,';
  806. $values[] = $feed_id;
  807. }
  808. $sub_search = rtrim($sub_search, ',');
  809. $sub_search .= ') ';
  810. }
  811. if ($filter->getLabelIds()) {
  812. if ($filter->getLabelIds() === '*') {
  813. $sub_search .= 'AND EXISTS (SELECT et.id_tag FROM `_entrytag` et WHERE et.id_entry = ' . $alias . 'id) ';
  814. } else {
  815. $sub_search .= 'AND ' . $alias . 'id IN (SELECT et.id_entry FROM `_entrytag` et WHERE et.id_tag IN (';
  816. foreach ($filter->getLabelIds() as $label_id) {
  817. $sub_search .= '?,';
  818. $values[] = $label_id;
  819. }
  820. $sub_search = rtrim($sub_search, ',');
  821. $sub_search .= ')) ';
  822. }
  823. }
  824. if ($filter->getNotLabelIds()) {
  825. if ($filter->getNotLabelIds() === '*') {
  826. $sub_search .= 'AND NOT EXISTS (SELECT et.id_tag FROM `_entrytag` et WHERE et.id_entry = ' . $alias . 'id) ';
  827. } else {
  828. $sub_search .= 'AND ' . $alias . 'id NOT IN (SELECT et.id_entry FROM `_entrytag` et WHERE et.id_tag IN (';
  829. foreach ($filter->getNotLabelIds() as $label_id) {
  830. $sub_search .= '?,';
  831. $values[] = $label_id;
  832. }
  833. $sub_search = rtrim($sub_search, ',');
  834. $sub_search .= ')) ';
  835. }
  836. }
  837. if ($filter->getLabelNames()) {
  838. $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 (';
  839. foreach ($filter->getLabelNames() as $label_name) {
  840. $sub_search .= '?,';
  841. $values[] = $label_name;
  842. }
  843. $sub_search = rtrim($sub_search, ',');
  844. $sub_search .= ')) ';
  845. }
  846. if ($filter->getNotLabelNames()) {
  847. $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 (';
  848. foreach ($filter->getNotLabelNames() as $label_name) {
  849. $sub_search .= '?,';
  850. $values[] = $label_name;
  851. }
  852. $sub_search = rtrim($sub_search, ',');
  853. $sub_search .= ')) ';
  854. }
  855. if ($filter->getAuthor()) {
  856. foreach ($filter->getAuthor() as $author) {
  857. $sub_search .= 'AND ' . $alias . 'author LIKE ? ';
  858. $values[] = "%{$author}%";
  859. }
  860. }
  861. if ($filter->getIntitle()) {
  862. foreach ($filter->getIntitle() as $title) {
  863. $sub_search .= 'AND ' . $alias . 'title LIKE ? ';
  864. $values[] = "%{$title}%";
  865. }
  866. }
  867. if ($filter->getTags()) {
  868. foreach ($filter->getTags() as $tag) {
  869. $sub_search .= 'AND ' . static::sqlConcat('TRIM(' . $alias . 'tags) ', " ' #'") . ' LIKE ? ';
  870. $values[] = "%{$tag} #%";
  871. }
  872. }
  873. if ($filter->getInurl()) {
  874. foreach ($filter->getInurl() as $url) {
  875. $sub_search .= 'AND ' . $alias . 'link LIKE ? ';
  876. $values[] = "%{$url}%";
  877. }
  878. }
  879. if ($filter->getNotAuthor()) {
  880. foreach ($filter->getNotAuthor() as $author) {
  881. $sub_search .= 'AND ' . $alias . 'author NOT LIKE ? ';
  882. $values[] = "%{$author}%";
  883. }
  884. }
  885. if ($filter->getNotIntitle()) {
  886. foreach ($filter->getNotIntitle() as $title) {
  887. $sub_search .= 'AND ' . $alias . 'title NOT LIKE ? ';
  888. $values[] = "%{$title}%";
  889. }
  890. }
  891. if ($filter->getNotTags()) {
  892. foreach ($filter->getNotTags() as $tag) {
  893. $sub_search .= 'AND ' . static::sqlConcat('TRIM(' . $alias . 'tags) ', " ' #'") . ' NOT LIKE ? ';
  894. $values[] = "%{$tag} #%";
  895. }
  896. }
  897. if ($filter->getNotInurl()) {
  898. foreach ($filter->getNotInurl() as $url) {
  899. $sub_search .= 'AND ' . $alias . 'link NOT LIKE ? ';
  900. $values[] = "%{$url}%";
  901. }
  902. }
  903. if ($filter->getSearch()) {
  904. foreach ($filter->getSearch() as $search_value) {
  905. if (static::isCompressed()) { // MySQL-only
  906. $sub_search .= 'AND CONCAT(' . $alias . 'title, UNCOMPRESS(' . $alias . 'content_bin)) LIKE ? ';
  907. $values[] = "%{$search_value}%";
  908. } else {
  909. $sub_search .= 'AND (' . $alias . 'title LIKE ? OR ' . $alias . 'content LIKE ?) ';
  910. $values[] = "%{$search_value}%";
  911. $values[] = "%{$search_value}%";
  912. }
  913. }
  914. }
  915. if ($filter->getNotSearch()) {
  916. foreach ($filter->getNotSearch() as $search_value) {
  917. if (static::isCompressed()) { // MySQL-only
  918. $sub_search .= 'AND CONCAT(' . $alias . 'title, UNCOMPRESS(' . $alias . 'content_bin)) NOT LIKE ? ';
  919. $values[] = "%{$search_value}%";
  920. } else {
  921. $sub_search .= 'AND ' . $alias . 'title NOT LIKE ? AND ' . $alias . 'content NOT LIKE ? ';
  922. $values[] = "%{$search_value}%";
  923. $values[] = "%{$search_value}%";
  924. }
  925. }
  926. }
  927. if ($sub_search != '') {
  928. if ($isOpen) {
  929. $search .= ' OR ';
  930. } else {
  931. $isOpen = true;
  932. }
  933. // Remove superfluous leading 'AND '
  934. $search .= '(' . substr($sub_search, 4) . ')';
  935. }
  936. }
  937. return [ $values, $search ];
  938. }
  939. /** @return array{0:array<int|string>,1:string} */
  940. protected function sqlListEntriesWhere(string $alias = '', ?FreshRSS_BooleanSearch $filters = null,
  941. int $state = FreshRSS_Entry::STATE_ALL,
  942. string $order = 'DESC', string $firstId = '', int $date_min = 0) {
  943. $search = ' ';
  944. $values = array();
  945. if ($state & FreshRSS_Entry::STATE_NOT_READ) {
  946. if (!($state & FreshRSS_Entry::STATE_READ)) {
  947. $search .= 'AND ' . $alias . 'is_read=0 ';
  948. }
  949. } elseif ($state & FreshRSS_Entry::STATE_READ) {
  950. $search .= 'AND ' . $alias . 'is_read=1 ';
  951. }
  952. if ($state & FreshRSS_Entry::STATE_FAVORITE) {
  953. if (!($state & FreshRSS_Entry::STATE_NOT_FAVORITE)) {
  954. $search .= 'AND ' . $alias . 'is_favorite=1 ';
  955. }
  956. } elseif ($state & FreshRSS_Entry::STATE_NOT_FAVORITE) {
  957. $search .= 'AND ' . $alias . 'is_favorite=0 ';
  958. }
  959. switch ($order) {
  960. case 'DESC':
  961. case 'ASC':
  962. break;
  963. default:
  964. throw new FreshRSS_EntriesGetter_Exception('Bad order in Entry->listByType: [' . $order . ']!');
  965. }
  966. if ($firstId !== '') {
  967. $search .= 'AND ' . $alias . 'id ' . ($order === 'DESC' ? '<=' : '>=') . ' ? ';
  968. $values[] = $firstId;
  969. }
  970. if ($date_min > 0) {
  971. $search .= 'AND ' . $alias . 'id >= ? ';
  972. $values[] = $date_min . '000000';
  973. }
  974. if ($filters && count($filters->searches()) > 0) {
  975. list($filterValues, $filterSearch) = self::sqlBooleanSearch($alias, $filters);
  976. $filterSearch = trim($filterSearch);
  977. if ($filterSearch !== '') {
  978. $search .= 'AND (' . $filterSearch . ') ';
  979. $values = array_merge($values, $filterValues);
  980. }
  981. }
  982. return array($values, $search);
  983. }
  984. /**
  985. * @phpstan-param 'a'|'A'|'s'|'S'|'c'|'f'|'t'|'T'|'ST' $type
  986. * @param int $id category/feed/tag ID
  987. * @return array{0:array<int|string>,1:string}
  988. */
  989. private function sqlListWhere(string $type = 'a', int $id = 0, int $state = FreshRSS_Entry::STATE_ALL,
  990. string $order = 'DESC', int $limit = 1, string $firstId = '', ?FreshRSS_BooleanSearch $filters = null,
  991. int $date_min = 0) {
  992. if (!$state) {
  993. $state = FreshRSS_Entry::STATE_ALL;
  994. }
  995. $where = '';
  996. $values = array();
  997. switch ($type) {
  998. case 'a': //All PRIORITY_MAIN_STREAM
  999. $where .= 'f.priority > ' . FreshRSS_Feed::PRIORITY_NORMAL . ' ';
  1000. break;
  1001. case 'A': //All except PRIORITY_ARCHIVED
  1002. $where .= 'f.priority >= ' . FreshRSS_Feed::PRIORITY_NORMAL . ' ';
  1003. break;
  1004. case 's': //Starred. Deprecated: use $state instead
  1005. $where .= 'f.priority >= ' . FreshRSS_Feed::PRIORITY_NORMAL . ' ';
  1006. $where .= 'AND e.is_favorite=1 ';
  1007. break;
  1008. case 'S': //Starred
  1009. $where .= 'e.is_favorite=1 ';
  1010. break;
  1011. case 'c': //Category
  1012. $where .= 'f.priority >= ' . FreshRSS_Feed::PRIORITY_NORMAL . ' ';
  1013. $where .= 'AND f.category=? ';
  1014. $values[] = $id;
  1015. break;
  1016. case 'f': //Feed
  1017. $where .= 'e.id_feed=? ';
  1018. $values[] = $id;
  1019. break;
  1020. case 't': //Tag (label)
  1021. $where .= 'et.id_tag=? ';
  1022. $values[] = $id;
  1023. break;
  1024. case 'T': //Any tag (label)
  1025. $where .= '1=1 ';
  1026. break;
  1027. case 'ST': //Starred or tagged (label)
  1028. $where .= 'e.is_favorite=1 OR EXISTS (SELECT et2.id_tag FROM `_entrytag` et2 WHERE et2.id_entry = e.id) ';
  1029. break;
  1030. default:
  1031. throw new FreshRSS_EntriesGetter_Exception('Bad type in Entry->listByType: [' . $type . ']!');
  1032. }
  1033. list($searchValues, $search) = $this->sqlListEntriesWhere('e.', $filters, $state, $order, $firstId, $date_min);
  1034. return array(array_merge($values, $searchValues),
  1035. 'SELECT '
  1036. . ($type === 'T' ? 'DISTINCT ' : '')
  1037. . 'e.id FROM `_entry` e '
  1038. . 'INNER JOIN `_feed` f ON e.id_feed = f.id '
  1039. . ($type === 't' || $type === 'T' ? 'INNER JOIN `_entrytag` et ON et.id_entry = e.id ' : '')
  1040. . 'WHERE ' . $where
  1041. . $search
  1042. . 'ORDER BY e.id ' . $order
  1043. . ($limit > 0 ? ' LIMIT ' . intval($limit) : '')); //TODO: See http://explainextended.com/2009/10/23/mysql-order-by-limit-performance-late-row-lookups/
  1044. }
  1045. /**
  1046. * @phpstan-param 'a'|'A'|'s'|'S'|'c'|'f'|'t'|'T'|'ST' $type
  1047. * @param int $id category/feed/tag ID
  1048. * @return PDOStatement|false
  1049. */
  1050. private function listWhereRaw(string $type = 'a', int $id = 0, int $state = FreshRSS_Entry::STATE_ALL,
  1051. string $order = 'DESC', int $limit = 1, string $firstId = '', ?FreshRSS_BooleanSearch $filters = null,
  1052. int $date_min = 0) {
  1053. list($values, $sql) = $this->sqlListWhere($type, $id, $state, $order, $limit, $firstId, $filters, $date_min);
  1054. $sql = 'SELECT e0.id, e0.guid, e0.title, e0.author, '
  1055. . (static::isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  1056. . ', e0.link, e0.date, e0.is_read, e0.is_favorite, e0.id_feed, e0.tags, e0.attributes '
  1057. . 'FROM `_entry` e0 '
  1058. . 'INNER JOIN ('
  1059. . $sql
  1060. . ') e2 ON e2.id=e0.id '
  1061. . 'ORDER BY e0.id ' . $order;
  1062. $stm = $this->pdo->prepare($sql);
  1063. if ($stm && $stm->execute($values)) {
  1064. return $stm;
  1065. } else {
  1066. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  1067. if ($this->autoUpdateDb($info)) {
  1068. return $this->listWhereRaw($type, $id, $state, $order, $limit, $firstId, $filters, $date_min);
  1069. }
  1070. Minz_Log::error('SQL error listWhereRaw: ' . $info[2]);
  1071. return false;
  1072. }
  1073. }
  1074. /**
  1075. * @param int $id category/feed/tag ID
  1076. * @return Traversable<FreshRSS_Entry>
  1077. */
  1078. public function listWhere(string $type = 'a', int $id = 0, int $state = FreshRSS_Entry::STATE_ALL,
  1079. string $order = 'DESC', int $limit = 1, string $firstId = '',
  1080. ?FreshRSS_BooleanSearch $filters = null, int $date_min = 0): Traversable {
  1081. $stm = $this->listWhereRaw($type, $id, $state, $order, $limit, $firstId, $filters, $date_min);
  1082. if ($stm) {
  1083. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  1084. yield FreshRSS_Entry::fromArray($row);
  1085. }
  1086. }
  1087. }
  1088. /**
  1089. * @param array<string> $ids
  1090. * @return Traversable<FreshRSS_Entry>
  1091. */
  1092. public function listByIds(array $ids, string $order = 'DESC'): Traversable {
  1093. if (count($ids) < 1) {
  1094. return;
  1095. }
  1096. if (count($ids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  1097. // Split a query with too many variables parameters
  1098. $idsChunks = array_chunk($ids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  1099. foreach ($idsChunks as $idsChunk) {
  1100. foreach ($this->listByIds($idsChunk, $order) as $entry) {
  1101. yield $entry;
  1102. }
  1103. }
  1104. return;
  1105. }
  1106. $sql = 'SELECT id, guid, title, author, '
  1107. . (static::isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  1108. . ', link, date, is_read, is_favorite, id_feed, tags, attributes '
  1109. . 'FROM `_entry` '
  1110. . 'WHERE id IN (' . str_repeat('?,', count($ids) - 1). '?) '
  1111. . 'ORDER BY id ' . $order;
  1112. $stm = $this->pdo->prepare($sql);
  1113. $stm->execute($ids);
  1114. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  1115. yield FreshRSS_Entry::fromArray($row);
  1116. }
  1117. }
  1118. /**
  1119. * @phpstan-param 'a'|'A'|'s'|'S'|'c'|'f'|'t'|'T'|'ST' $type
  1120. * @param int $id category/feed/tag ID
  1121. * @return array<numeric-string>|false
  1122. */
  1123. public function listIdsWhere(string $type = 'a', int $id = 0, int $state = FreshRSS_Entry::STATE_ALL,
  1124. string $order = 'DESC', int $limit = 1, string $firstId = '', ?FreshRSS_BooleanSearch $filters = null) {
  1125. [$values, $sql] = $this->sqlListWhere($type, $id, $state, $order, $limit, $firstId, $filters);
  1126. $stm = $this->pdo->prepare($sql);
  1127. $stm->execute($values);
  1128. return $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  1129. }
  1130. /**
  1131. * @param array<string> $guids
  1132. * @return array<string>|false
  1133. */
  1134. public function listHashForFeedGuids(int $id_feed, array $guids) {
  1135. $result = [];
  1136. if (count($guids) < 1) {
  1137. return $result;
  1138. } elseif (count($guids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  1139. // Split a query with too many variables parameters
  1140. $guidsChunks = array_chunk($guids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  1141. foreach ($guidsChunks as $guidsChunk) {
  1142. $result += $this->listHashForFeedGuids($id_feed, $guidsChunk);
  1143. }
  1144. return $result;
  1145. }
  1146. $guids = array_unique($guids);
  1147. $sql = 'SELECT guid, ' . static::sqlHexEncode('hash') .
  1148. ' AS hex_hash FROM `_entry` WHERE id_feed=? AND guid IN (' . str_repeat('?,', count($guids) - 1). '?)';
  1149. $stm = $this->pdo->prepare($sql);
  1150. $values = array($id_feed);
  1151. $values = array_merge($values, $guids);
  1152. if ($stm && $stm->execute($values)) {
  1153. $rows = $stm->fetchAll(PDO::FETCH_ASSOC);
  1154. foreach ($rows as $row) {
  1155. $result[$row['guid']] = $row['hex_hash'];
  1156. }
  1157. return $result;
  1158. } else {
  1159. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  1160. if ($this->autoUpdateDb($info)) {
  1161. return $this->listHashForFeedGuids($id_feed, $guids);
  1162. }
  1163. Minz_Log::error('SQL error listHashForFeedGuids: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
  1164. . ' while querying feed ' . $id_feed);
  1165. return false;
  1166. }
  1167. }
  1168. /**
  1169. * @param array<string> $guids
  1170. * @return int|false The number of affected feeds, or false if error
  1171. */
  1172. public function updateLastSeen(int $id_feed, array $guids, int $mtime = 0) {
  1173. if (count($guids) < 1) {
  1174. return 0;
  1175. } elseif (count($guids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  1176. // Split a query with too many variables parameters
  1177. $affected = 0;
  1178. $guidsChunks = array_chunk($guids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  1179. foreach ($guidsChunks as $guidsChunk) {
  1180. $affected += $this->updateLastSeen($id_feed, $guidsChunk, $mtime);
  1181. }
  1182. return $affected;
  1183. }
  1184. $sql = 'UPDATE `_entry` SET `lastSeen`=? WHERE id_feed=? AND guid IN (' . str_repeat('?,', count($guids) - 1). '?)';
  1185. $stm = $this->pdo->prepare($sql);
  1186. if ($mtime <= 0) {
  1187. $mtime = time();
  1188. }
  1189. $values = array($mtime, $id_feed);
  1190. $values = array_merge($values, $guids);
  1191. if ($stm && $stm->execute($values)) {
  1192. return $stm->rowCount();
  1193. } else {
  1194. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  1195. if ($this->autoUpdateDb($info)) {
  1196. return $this->updateLastSeen($id_feed, $guids);
  1197. }
  1198. Minz_Log::error('SQL error updateLastSeen: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
  1199. . ' while updating feed ' . $id_feed);
  1200. return false;
  1201. }
  1202. }
  1203. /** @return array<string,int>|false */
  1204. public function countUnreadRead() {
  1205. $sql = 'SELECT COUNT(e.id) AS count FROM `_entry` e INNER JOIN `_feed` f ON e.id_feed=f.id WHERE f.priority > 0'
  1206. . ' UNION SELECT COUNT(e.id) AS count FROM `_entry` e INNER JOIN `_feed` f ON e.id_feed=f.id WHERE f.priority > 0 AND e.is_read=0';
  1207. $stm = $this->pdo->query($sql);
  1208. if ($stm === false) {
  1209. return false;
  1210. }
  1211. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  1212. rsort($res);
  1213. $all = empty($res[0]) ? 0 : (int)$res[0];
  1214. $unread = empty($res[1]) ? 0 : (int)$res[1];
  1215. return array('all' => $all, 'unread' => $unread, 'read' => $all - $unread);
  1216. }
  1217. /** @return int|false */
  1218. public function count(?int $minPriority = null) {
  1219. $sql = 'SELECT COUNT(e.id) AS count FROM `_entry` e';
  1220. if ($minPriority !== null) {
  1221. $sql .= ' INNER JOIN `_feed` f ON e.id_feed=f.id';
  1222. $sql .= ' WHERE f.priority > ' . $minPriority;
  1223. }
  1224. $stm = $this->pdo->query($sql);
  1225. if ($stm == false) {
  1226. return false;
  1227. }
  1228. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  1229. return isset($res[0]) ? intval($res[0]) : 0;
  1230. }
  1231. public function countNotRead(?int $minPriority = null): int {
  1232. $sql = 'SELECT COUNT(e.id) AS count FROM `_entry` e';
  1233. if ($minPriority !== null) {
  1234. $sql .= ' INNER JOIN `_feed` f ON e.id_feed=f.id';
  1235. }
  1236. $sql .= ' WHERE e.is_read=0';
  1237. if ($minPriority !== null) {
  1238. $sql .= ' AND f.priority > ' . $minPriority;
  1239. }
  1240. $stm = $this->pdo->query($sql);
  1241. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  1242. return isset($res[0]) ? intval($res[0]) : 0;
  1243. }
  1244. /** @return array<string,int>|false */
  1245. public function countUnreadReadFavorites() {
  1246. $sql = <<<'SQL'
  1247. SELECT c FROM (
  1248. SELECT COUNT(e1.id) AS c, 1 AS o
  1249. FROM `_entry` AS e1
  1250. JOIN `_feed` AS f1 ON e1.id_feed = f1.id
  1251. WHERE e1.is_favorite = 1
  1252. AND f1.priority >= :priority_normal1
  1253. UNION
  1254. SELECT COUNT(e2.id) AS c, 2 AS o
  1255. FROM `_entry` AS e2
  1256. JOIN `_feed` AS f2 ON e2.id_feed = f2.id
  1257. WHERE e2.is_favorite = 1
  1258. AND e2.is_read = 0
  1259. AND f2.priority >= :priority_normal2
  1260. ) u
  1261. ORDER BY o
  1262. SQL;
  1263. $stm = $this->pdo->prepare($sql);
  1264. if (!$stm) {
  1265. Minz_Log::error('SQL error in ' . __method__ . ' ' . json_encode($this->pdo->errorInfo()));
  1266. return false;
  1267. }
  1268. //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
  1269. $stm->bindValue(':priority_normal1', FreshRSS_Feed::PRIORITY_NORMAL, PDO::PARAM_INT);
  1270. $stm->bindValue(':priority_normal2', FreshRSS_Feed::PRIORITY_NORMAL, PDO::PARAM_INT);
  1271. $stm->execute();
  1272. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  1273. rsort($res);
  1274. $all = empty($res[0]) ? 0 : intval($res[0]);
  1275. $unread = empty($res[1]) ? 0 : intval($res[1]);
  1276. return array('all' => $all, 'unread' => $unread, 'read' => $all - $unread);
  1277. }
  1278. }