EntryDAO.php 48 KB

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