EntryDAO.php 49 KB

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