EntryDAO.php 50 KB

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