EntryDAO.php 49 KB

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